3

TABLES:

Players

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

Transactions

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

My goal is to fetch all data, maintaining all the players, even with null values in following query:

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

nevertheless results omit null value, example:

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

What I would like to have is mention about the empty value:

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

What do I miss here? Actually I use QueryDSL for that, but translated example into pure SQL since it behaves in the same manner.

krzakov
  • 3,871
  • 11
  • 37
  • 52
  • 1
    So there is no record in the Transactions table but you want it returned from the player table anyway? If so change your inner join to left join (you may have to change your sum to do a isnull check sum(IsNull(t.value, 0))) – Brad Apr 27 '18 at 14:12

5 Answers5

8

using LEFT JOIN and coalesce function

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
D-Shih
  • 44,943
  • 6
  • 31
  • 51
2

Change your JOIN to a LEFT JOIN, then add IFNULL(value, 0) in your SUM()

Aurelien
  • 1,497
  • 7
  • 15
2

left join keeps all the rows in the left table

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

You might be looking for count(t.value) rather than count(*)

paparazzo
  • 44,497
  • 23
  • 105
  • 176
1

I'm just offering this so you have a correct answer:

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;

You need to pay attention to the aggregation functions as well as the JOIN.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Please Try This:

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

Hope this helps.

Ameya
  • 78
  • 1
  • 11