如何按天对这些数据进行SQL PIVOT?

时间:2019-06-01 01:57:14

标签: sql sql-server sql-server-2016

使用下面的模式和表,显示表的示例输出,我试图“ PIVOT”此数据以使其具有由SERIAL和AREA组成的行,每一列都是每个“ NIGHTOF”记录的COMPLIANCE。理想输出也如下所示。不管我读过多少次示例,我都无法绕过PIVOT语法...

架构和表:

SELECT [CONTID], [AREA], [NIGHTOF], [COMPLIANCE] FROM ComplianceScores

常规输出:

CONTID  NIGHTOF     AREA    COMPLIANCE
001     2014-01-01  Room 2  28
001     2014-01-01  Room 2  18
001     2014-01-01  Room 2  20
003     2014-01-02  Room 1  18
003     2014-01-02  Room 1  70
003     2014-01-02  Room 1  80
008     2014-01-03  Room 1  0
009     2014-01-04  Room 1  35

理想的输出:

CONTID  AREA    2014-01-01   2014-01-02    2014-01-03
001     Room 2  28           18            20
003     Room 1  18           70            80

1 个答案:

答案 0 :(得分:1)

我同意@Sparky,认为您的数据和输出不匹配。

我认为您的数据本来应该是这样的:

create table ComplianceScores (
  CONTID char(3),
  NIGHTOF date,
  AREA varchar(10),
  COMPLIANCE int
  )

insert ComplianceScores (CONTID, NIGHTOF, AREA, COMPLIANCE)
values ('001', '2014-01-01', 'Room 2', 28)
, ('001', '2014-01-02', 'Room 2', 18)
, ('001', '2014-01-03', 'Room 2', 20)
, ('003', '2014-01-01', 'Room 1', 18)
, ('003', '2014-01-02', 'Room 1', 70)
, ('003', '2014-01-03', 'Room 1', 80)

我想您正在寻找此SQL:

select ContId, Area, [2014-01-01], [2014-01-02], [2014-01-03]  
  from (select Area, ContId, NightOf, Compliance
          from ComplianceScores) SourceTable  
pivot
(  
  sum(Compliance)  
  for NightOf in ([2014-01-01], [2014-01-02], [2014-01-03])  
) pt;