T-SQL如何将列汇总为行?

时间:2019-02-04 06:51:38

标签: sql sql-server tsql

我需要根据旧记录生成一个汇总表:

 Ref     Name   count11 count12     Name2   count21 count22     Name3     count31 count32 
========================================================================================
1        item1       2      0      item2       0      1         item3       120    0  
2        item1       32     3      item2       3      1         item3       3      5    
3        item1       0      2      item2       0      0         item3       0      5    
4        item1       12     1      item2       1      1         item3       1      1    
5        item1       0      0      item2       0      0         item3       0      0    

总结“计数”列:

Ref     items       count1      count2
========================================
1       item1       46          6
2       item2       4           3
3       item3       124         11

如何存档? 谢谢。

2 个答案:

答案 0 :(得分:1)

我们可以尝试进行数据透视查询,但是要在CTE上为所有项目创建一个逻辑列:

WITH cte AS (
    SELECT Name, count11 AS count1, count12 AS count2 FROM yourTable UNION ALL
    SELECT Name, count21, count22 FROM yourTable UNION ALL
    SELECT Name, count31, count32 FROM yourTable
)

SELECT
    Name AS items,
    SUM(count1) AS count1,
    SUM(count2) AS count2
FROM cte
GROUP BY
    Name
ORDER BY
    Name;

我省略了Ref列,因为您期望的输出中的值实际上与原始数据没有任何关系。如果需要在输出中使用序列,则可以使用ROW_NUMBER进行一些排序。

答案 1 :(得分:1)

我会使用APPLY

SELECT tt.Ref, tt.items, SUM([count1]), SUM([count2])
FROM table t CROSS APPLY
     ( VALUES (1, [Name],  [count11], [count12]), 
              (2, [Name2], [count21], [count22]), 
              (3, [Name3], [count31], [count32]) 
     ) tt(Ref, items, [count1], [count2])
GROUP BY tt.Ref, tt.items;