堆垛, 当用SQL语法编写时,我一直在努力理解PIVOT ......
我的数据格式:
CONTID STCODE
8203 BA
8203 BA
8203 UY
8203 UY
8203 UY
8203 FA
8203 FA
8203 FA
8203 UY
8203 UY
8203 *LC
8203 *LC
8203 *LC
8203 UY
预期输出:
CONTID BA *LC UY FA
8203 2 3 6 3
到目前为止我的可怕尝试......(我不知道在括号或SELECT子句中放什么。
SELECT c.CONTID, [STCODE] AS 'Burglary Alarm', [STCODE] AS 'Late-to-close'
FROM CUSTOMER c LEFT JOIN CLOGS15 h ON c.SERIALNO = h.SERIALNO
PIVOT
(
SUM(h.STCODE)
FOR h.STCODE
IN ([BA], [*LC])
) AS pvt
答案 0 :(得分:0)
试试这个
SELECT
CONTID,
[BA] AS 'Burglary Alarm',
[*LC] AS 'Late-to-close',
[UY],
[FA]
FROM
(
SELECT c.CONTID,
[STCODE]
FROM CUSTOMER c
LEFT JOIN CLOGS15 h ON c.SERIALNO = h.SERIALNO
WHERE C.CONTID LIKE '8203' AND h.EVTYPE = 1
AND DATEADD(hour,-6,h.EVDATE)
BETWEEN '2015-02-23 06:30:00.000' AND '2015-02-24 06:30:00.000'
) SRC
PIVOT
(
COUNT(SRC.STCODE)
FOR SRC.STCODE IN ([BA], [*LC], [UY], [FA])
) AS pvt