繁体   English   中英

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

[英]T-SQL How to sum columns into rows?

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

 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

我该如何存档? 谢谢。

我们可以尝试进行数据透视查询,但是要在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

我会使用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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM