0

How to avoid NULL values in CASE and SUM by P.Id. Problem is that i have more than one DPB.ProductTypeId in DPB table

SELECT  P.[Id], 
        CASE 
        WHEN DPB.ProductTypeId = 1 THEN SUM(DPB.BonusAmount)
        END AS [CasinoBonus]
FROM Player P           
JOIN PlayerBonus DPB ON P.[Id] = DPB.[PlayerId]
group by P.[Id],DPB.ProductTypeId
3
  • 1
    add some sample data and your expected output. and also add what issue you are facing. Commented Jul 19, 2019 at 9:16
  • sum already ignores null values. Commented Jul 19, 2019 at 9:17
  • If i put sum i got two rows, one with summarized values and one NULL Commented Jul 19, 2019 at 9:20

2 Answers 2

1

use case when inside sum

 SELECT  P.[Id], 
            sum(CASE 
            WHEN DPB.ProductTypeId = 1 THEN DPB.BonusAmount
            else 0
            END) AS [CasinoBonus]
    FROM Player P           
    JOIN PlayerBonus DPB ON P.[Id] = DPB.[PlayerId]
    where P.[Id] is not null and DPB.[PlayerId] is not null
    group by P.[Id],DPB.ProductTypeId
Sign up to request clarification or add additional context in comments.

1 Comment

Your CASE expression might need an ELSE 0 case.
1

The case should be the argument to the sum(). You query should look like this:

SELECT P.[Id], 
       SUM(CASE WHEN DPB.ProductTypeId = 1 THEN DPB.BonusAmount
           END) AS [CasinoBonus]
FROM Player P JOIN
     PlayerBonus DPB
     ON P.[Id] = DPB.[PlayerId]
GROUP BY P.[Id];

Note that you don't want DPB.ProductTypeId in the GROUP BY.

That said, you may simply want:

SELECT P.[Id], 
       SUM(DPB.BonusAmount) AS [CasinoBonus]
FROM Player P LEFT JOIN
     PlayerBonus DPB
     ON P.[Id] = DPB.[PlayerId] AND 
        DPB.ProductTypeId = 1
GROUP BY P.[Id];

Moving the condition to the WHERE clause removes the need for the CASE entirely. The LEFT JOIN keeps all players, even those that don't have that product type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.