使用SUM进行GROUP BY而不删除空(null)值

时间:2018-04-27 14:08:43

标签: sql group-by querydsl sql-function

TABLES:

球员

player_no   | transaction_id
----------------------------
1           | 11
2           | 22
3           | (null)
1           | 33

交易

id            | value   |
-----------------------
11            | 5
22            | 10
33            | 2

我的目标是获取所有数据,维护所有玩家,即使在以下查询中使用null值:

SELECT p.player_no, COUNT(p.player_no), SUM(t.value) FROM Players p 
INNER JOIN Transactions t ON p.transaction_id = t.id 
GROUP BY p.player_no

然而结果省略了空值,例如:

player_no | count  | sum
------------------------
1         | 2      |  7
2         | 1      |  10

我想提到的是空值:

player_no | count  | sum
------------------------
1         | 2      |  7
2         | 1      |  10
3         | 0      |  0

我在这里想念什么? 实际上我使用QueryDSL,但是将示例转换为纯SQL,因为它的行为方式相同。

5 个答案:

答案 0 :(得分:7)

使用LEFT JOINcoalesce函数

SELECT p.player_no, COUNT(p.player_no), coalesce(SUM(t.value),0) 
FROM Players p 
LEFT JOIN Transactions t ON p.transaction_id = t.id 
GROUP BY p.player_no

答案 1 :(得分:2)

将您的JOIN更改为LEFT JOIN,然后在SUM()

中添加IFNULL(值,0)

答案 2 :(得分:2)

左连接保留左表中的所有行

SELECT p.player_no
     , COUNT(*) as count
     , SUM(isnull(t.value,0)) 
FROM Players p 
LEFT JOIN Transactions t 
       ON p.transaction_id = t.id 
GROUP BY p.player_no

您可能正在寻找count(t.value)而不是count(*)

答案 3 :(得分:1)

我只是提供这个,所以你有一个正确的答案:

SELECT p.player_no, COUNT(t.id) as [count], COALESCE(SUM(t.value), 0) as [sum]
FROM Players p LEFT JOIN
     Transactions t
     ON p.transaction_id = t.id 
GROUP BY p.player_no;

您需要注意聚合函数以及JOIN

答案 4 :(得分:0)

请试试这个:

SELECT P.player_no,
   COUNT(*) as count,
   SUM(isnull(T.value,0)) 
FROM Players P 
LEFT JOIN Transactions T 
   ON P.transaction_id = T.id 
GROUP BY P.player_no

希望这有帮助。