如何按日期按代码对同一行上的小计进行分组

时间:2017-10-23 13:24:02

标签: sql sql-server grouping subtotal

我在这里找不到与此问题相同的问题。如果这是重复,请道歉 基本上我有一个交易表。每个交易都有一个代码和一个日期时间戳。我希望能够创建一个SQL查询,以便结果看起来像这样

+------------+--------+--------+-------+--------+-------+--------+
|    DATE    | CODE1  | COUNT1 | CODE2 | COUNT2 | CODE3 | COUNT3 |
+------------+--------+--------+-------+--------+-------+--------+
| 2017-01-01 | George |     12 | John  |     10 | Ringo |    114 |
+------------+--------+--------+-------+--------+-------+--------+

我目前有一个查询,我可以在各行上拉小计,即:

SELECT CONVERT(mytime AS DATE), code, COUNT(*) FROM transactiontable
GROUP BY CONVERT(mytime AS DATE), code
ORDER BY CONVERT(mytime AS DATE), code

会给我

DATE             CODE       COUNT
-----------------------------------
2017-01-01       George      12
2017-01-01        John       10
等等......

我目前没有单独的代码表,但我正在考虑它。

谢谢!

2 个答案:

答案 0 :(得分:2)

您也可以使用PIVOT进行此操作。

DECLARE @Table TABLE (DATE DATETIME,  CODE  VARCHAR(10), [COUNT] INT)
INSERT INTO @Table

VALUES
('2017-01-01','George',12),
('2017-01-01','John',10)

;WITH CTE AS 
(
    SELECT RN = ROW_NUMBER() OVER (ORDER BY DATE), * FROM @Table
)
SELECT * FROM 
        (SELECT DATE, CONCAT('CODE',RN) RN, CODE Value FROM CTE
        UNION ALL 
        SELECT DATE, CONCAT('COUNT',RN) RN,  CONVERT(VARCHAR,[COUNT]) Value FROM CTE
        ) SRC
PIVOT (MAX(Value) FOR RN IN ([CODE1],[COUNT1],[CODE2],[COUNT2])) PVT

结果:

DATE        CODE1       COUNT1      CODE2    COUNT2 
----------- ----------- ----------- -------- -------
2017-01-01  George      12          John     10

答案 1 :(得分:1)

您可以使用窗口函数row_number来形成组并使用条件聚合来进行透视:

select dt,
    max(case when rn = 1 then code end) as code_1,
    max(case when rn = 1 then cnt end) as code_1,
    max(case when rn = 2 then code end) as code_2,
    max(case when rn = 2 then cnt end) as code_2,
    max(case when rn = 3 then code end) as code_3,
    max(case when rn = 3 then cnt end) as code_3,
    ....
from (
    select convert(date, mytime) as dt, 
        code, 
        count(*),
        row_number() over (partition by convert(date, mytime) order by code) as rn
    from transactiontable
    group by convert(date, mytime), code
    ) t
group by dt
order by dt;