行到列的总和

Posted

技术标签:

【中文标题】行到列的总和【英文标题】:Sum of rows to columns 【发布时间】:2021-05-15 17:58:19 【问题描述】:

我有一个表 (tbl_liabilities) 有 4 列,如下所示:

+------------+------------+-------+------------+  
| User_id    | Name       | Type  |  Amount    |
+------------+------------+-------+------------+    

现在想象这样的记录。

1| Luigi | Housing  | 100
1| Luigi | Housing  | 200
1| Luigi | Housing  | 150
1| Luigi | Mortage  | 60
1| Luigi | Mortage  | 30
1| Luigi | Revolving| 60
1| Luigi | Other    | 100
1| Luigi | Housing  | 100
2| Toad  | Housing  | 200
2| Toad  | Revolving| 150
2| Toad  | Revolving| 60
2| Toad  | Revolving| 30
2| Toad  | Other    | 60
2| Toad  | Other    | 100

我正在寻找一个查询,该查询返回每个客户的每种负债(住房、抵押、循环、其他)的总和和计数

输出应该是这样的。

+------------+------------+...|---------------+------------------+  
| User_id    | Name       |...|(Liability)Sum |  (Liability)Count|
+------------+------------+...+---------------+------------------+    

例如对于上述表格,结果将是。

id, name, h_sum, h_count, M_sum, M_count, R_sum, R_count, O_sum, O_count,

id|  name |h_sum|h_count|M_sum|M_count|R_sum|R_count|O_sum|O_count 
1 | Luigi | 550 |   4   |  90 |   2   |  60 |   1   | 100 |   1 
2 | Toad  | 100 |   1   |  0  |   0   | 240 |   3   | 160 |   2 

欢迎任何线索或帮助,提前感谢您的时间。

【问题讨论】:

【参考方案1】:

您可以使用条件聚合:

select id, name,
       sum(case when type = 'Housing' then amount end) as h_sum,
       sum(case when type = 'Housing' then 1 else 0 end) as h_count,
       sum(case when type = 'Mortage' then amount end) as m_sum,
       sum(case when type = 'Mortage' then 1 else 0 end) as m_count,
       sum(case when type = 'Revolving' then amount end) as r_sum,
       sum(case when type = 'Revolving' then 1 else 0 end) as r_count,
       sum(case when type = 'Other' then amount end) as o_sum,
       sum(case when type = 'Other' then 1 else 0 end) as o_count
from t
group by id, name;

【讨论】:

【参考方案2】:

你真的需要这个带有“硬编码”列的输出吗?

我将只使用以下查询并稍后解释它:

SELECT id, name, type, COUNT(*), SUM(amount)
FROM t
GROUP BY id, name, type

【讨论】:

以上是关于行到列的总和的主要内容,如果未能解决你的问题,请参考以下文章

从行到列的 SQL 结果

具有两行到列的数据透视表

如何在 sql server 2008 中编写对行到列的查询?

MySQL - 行到列

调整多级行到列查询

sql server中的表行到列