如何创建汇总表?

时间:2018-09-18 14:37:22

标签: sql sql-server sql-server-2008 sql-server-2012

我有行:

PLACE   DATE_OPEN   SUM
-----------------------
PLACE1  03.09.2018  2
PLACE2  03.09.2018  2
PLACE1  04.09.2018  8
PLACE1  05.09.2018  9
PLACE2  05.09.2018  1

我使用此SQL查询获取行:

SELECT
    SB AS [PLACE], 
    CAST(OPEN_TIME AS DATE) AS [DATE_OPEN], 
    COUNT(ID) AS [SUM]
FROM
    [Table]
WHERE
    SB IN ('PLACE1', 'PLACE2')
GROUP BY 
    SB, CAST(OPEN_TIME AS DATE)

我想以摘要表的形式获取表,是否可以使用SQL做到这一点?

所需输出的示例:

PLACE   DATE_OPEN   
        03.09.2018  04.09.2018  05.09.2018
PLACE1  2           8           9
PLACE2  2                       1

1 个答案:

答案 0 :(得分:1)

最近的是PIVOT:

WITH Demo AS
(
    SELECT * FROM (VALUES
    ('PLACE1', '03.09.2018', 2),
    ('PLACE2', '03.09.2018', 2),
    ('PLACE1', '04.09.2018', 8),
    ('PLACE1', '05.09.2018', 9),
    ('PLACE2', '05.09.2018', 1)) T(PLACE, DATE_OPEN, [SUM])
)
SELECT * FROM Demo
PIVOT (SUM([Sum]) FOR Date_Open IN ([03.09.2018],[04.09.2018],[05.09.2018])) P

结果

PLACE  03.09.2018  04.09.2018  05.09.2018
------ ----------- ----------- -----------
PLACE1 2           8           9
PLACE2 2           NULL        1