SQL Server双列数据透视表

时间:2016-02-22 11:45:55

标签: sql-server tsql pivot

我试图创建一个PIVOT TSQL语句,按日期和州/省总计产品,并提供AVG Transit Time。以下是我到目前为止的情况:

select *
from    (select createdate [Date Processed], 
                stateprovince as [Province],
                count(*) as [Total],
                avg(datediff(day,createdate,t.eventdate)) as [AVG Delivery],
                product

            from recipient C left outer join 
            (select delivid, product, eventdesc, eventdate, eventcode
                from deliverystatus 
                where delivid in (select max(deliv_id) 
                                        from deliverystatus 
                                        where eventcode = 'DELIVERED' 
                                        group by product)) as t  ON c.product = t.product
            where account = 3519 and consol <>'' and trknum <> '' and C.createdate between '2/4/2016' and '2/4/2016'
            group by C.createdate, c.stateprovince, c.product
        ) as Q 
pivot   (
            count(product)
            for [Province] in (NY, IL, GA)
        ) as PVT

我的结果是:

Date Processed          Total   AVG Transit NY  IL  GA
2016-02-04 00:00:00.000 1       8           0   0   1
2016-02-04 00:00:00.000 1       11          2   4   1
2016-02-04 00:00:00.000 1       12          0   0   0
2016-02-04 00:00:00.000 1       15          0   0   0

我需要结果:

Date Processed          Total   AVG Transit NY  IL  GA
2016-02-04 00:00:00.000 8       11.5        2   4   2

最终目标是让州/省列出的AVG Transit如下:

Date Processed          Total   Total AVG   NY AVG  IL  AVG   GA AVG
2016-02-04 00:00:00.000 8       11.5        2   8   4   11    2  15

提前致谢。

1 个答案:

答案 0 :(得分:0)

您需要在数据透视后添加GROUP BY子句,并为每个输出列获取AVG SUMMAX值:

select [Date Processed], SUM(NY+IL+GA) AS [Total], AVG([AVG Delivery]) AS [AVG Delivery], SUM(NY) AS NY, SUM(IL) AS IL, SUM(GA) AS GA 
from    (select createdate [Date Processed], 
                stateprovince as [Province],
                count(*) as [Total],
                avg(datediff(day,createdate,t.eventdate)) as [AVG Delivery],
                product

            from recipient C left outer join 
            (select delivid, product, eventdesc, eventdate, eventcode
                from deliverystatus 
                where delivid in (select max(deliv_id) 
                                        from deliverystatus 
                                        where eventcode = 'DELIVERED' 
                                        group by product)) as t  ON c.product = t.product
            where account = 3519 and consol <>'' and trknum <> '' and C.createdate between '2/4/2016' and '2/4/2016'
            group by C.createdate, c.stateprovince, c.product
        ) as Q 
pivot   (
            count(product)
            for [Province] in (NY, IL, GA)
        ) as PVT
group by [Date Processed]