如何创建SQL Server数据透视表

时间:2018-12-10 17:10:09

标签: sql sql-server pivot-table

我正在尝试创建SQL Server PIVOT表,但是遇到麻烦。

这是我想要得到的结果:

enter image description here

这是我准备的SQL查询,但我迷路了。我该如何使其正常工作。

select *
from
    (select DESCRIPTION_, DISPLAYNAME, SUCCESFULRECORDCOUNT, FINISHDATETIME
     from LOGTABLE (NOLOCK)
    ) as X
pivot
     (sum(SUCCESFULRECORDCOUNT) for FINISHDATETIME in (GETDATE()-4)) as DAY1
pivot
     (sum(SUCCESFULRECORDCOUNT) for FINISHDATETIME in (GETDATE()-3)) as DAY2
pivot
     (sum(SUCCESFULRECORDCOUNT) for FINISHDATETIME in (GETDATE()-2)) as DAY2
pivot
     (sum(SUCCESFULRECORDCOUNT) for FINISHDATETIME in (GETDATE()-1)) as DAY3

2 个答案:

答案 0 :(得分:1)

https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=915122598b6f8f350127f79e21b3c12c

您需要将日期更改为文字值以在数据透视表中使用。

buildrev.py

答案 1 :(得分:1)

我认为您可以像

一样使用分组方式
SELECT DESCRIPTION_,DISPLAYNAME
,SUM(IIF(FINISHDATETIME IN (GETDATE()-4),SUCCESFULRECORDCOUNT,0)) AS 'DAY1'
,SUM(IIF(FINISHDATETIME IN (GETDATE()-3),SUCCESFULRECORDCOUNT,0)) AS 'DAY2'
,SUM(IIF(FINISHDATETIME IN (GETDATE()-2),SUCCESFULRECORDCOUNT,0)) AS 'DAY3'
,SUM(IIF(FINISHDATETIME IN (GETDATE()-1),SUCCESFULRECORDCOUNT,0)) AS 'DAY4'
FROM LOGTABLE  (NOLOCK)
GROUP BY 
DESCRIPTION_,
DISPLAYNAME