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

How to group subtotals on the same row by date, by code

我在这里找不到与此问题对应的问题。抱歉,如果这是重复 基本上我有一个 table 交易。每笔交易都有一个代码和一个日期时间戳。我希望能够创建一个 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

等...

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

谢谢!

您可以使用window函数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;

你也可以使用 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