How to Pivot data from one table with SQL server 2

2019-02-20 07:25发布

问题:

I would like to create a query from a single table with the following columns.

SEQNO is a unique key

Name   ID   Amount   Date          JOBID       SEQNO
Mark    9    200     1/2/09         1001         1
Peter   3    300     1/2/09         1001         2
Steve   1    200     2/2/09         1001         3
Mark    9    200     3/2/09         1001         4
Peter   3    300     4/2/09         1001         5
Steve   1    200     5/2/09         1001         6
Hally   1    200     5/2/09         1002         7

The query should output in this format by SUBJOBID and a date range:-

**NAME      ID      1/2       2/2     3/2     4/2     5/2      JOBID**<br>
Mark        9       200       NULL    200     NULL    NULL     1001   
Peter       3       300       NULL    NULL    300     NULL     1001   
Steve       1       NULL      200     NULL    NULL    200      1001   

I have been going over pivot queries for this. But I don't seem to get anywhere. Could some one help ?

回答1:

This actually can be done pretty easily with a PIVOT function. Since the other answer doesn't show the code associated with how to perform it, here are two ways to PIVOT the data.

First is with a Static Pivot. A static pivot is when you know the data ahead of time to turn into columns.

select *
from 
(
    select name, id, convert(char(5), dt, 101) dt, jobid, amount
    from test
) x
pivot
(
    sum(amount)
    for dt in ([01/02], [02/02], [03/02], [04/05], [05/05])
)p
order by jobid, name

See SQL Fiddle with Demo

The second way is by using a Dynamic PIVOT to identify at run-time the values to turn to columns.

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(char(5), dt, 101)) 
                    from test
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT name, id, ' + @cols + ', jobid from 
             (
                select  name, id, convert(char(5), dt, 101) dt, jobid, amount
                from test
            ) x
            pivot 
            (
                sum(amount)
                for dt in (' + @cols + ')
            ) p 
            order by jobid, name'

execute(@query)

See SQL Fiddle with Demo

Both will produce the same results. The Dynamic works great when you do not know the values ahead of time to convert to columns.