Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case When Distinct value then sum another value?

Piggy backing off another question I had yesterday.

I was wondering how I would go about counting the distinct number of records that have an amt > 1500. The way my data is joined, I could have the same PKey AcctNo reflected more than one time because my full outer joined to another table that has multiple transactional records.

(Case When AcctNo_PKey = distinct then sum(case when amount > 1500 then 1 else 0 end)
 else 0) end as GT1500

this my current code that produces a desired result. I

SELECT sum(case when amount > 1500 then 1 else 0 end) as GT1500
     , sum(case when amount < 1500 then 1 else 0 end) as LT1500
    , DATEPART(Year, amount.Date) Deposit_Year
    , DATEPART(QUARTER, amount.Date) Deposit_Qtr 
From account 
full outer JOIN amount ON account.AcctNo = amount.AcctNo
group by DATEPART(Year, amount.Date)
    , DATEPART(QUARTER, amount.Date)

Or maybe my entire approach is wrong...idk

like image 205
donviti Avatar asked Sep 05 '14 13:09

donviti


People also ask

Can we use distinct and sum together in SQL?

DISTINCT instructs the SUM() function to calculate the sum of the only distinct values. expression is any valid expression that returns an exact or approximate numeric value. Note that aggregate functions or subqueries are not accepted in the expression.

How do you use distinct and count together?

Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table. Display all records from the table using select statement.

Can we use distinct in case statement?

You can only apply distinct to the column expression, not to the THEN clause within the CASE.

Can we use SUM function in case statement?

Then comes the curious use of a SUM() with a CASE WHEN . This expression says whenever the number_of_lectures is higher than 20, the row is assigned the value 1. If the condition is not met, the assigned value is 0. The SUM() function will sum all those rows that have the assigned value equal to 1.


1 Answers

You can use COUNT(DISTINCT ) on the output of a CASE expression. For example, to count the number of distinct AcctNo_Pkeys that have an [amount] < 1500 row somewhere in the aggregated result, you could use this:

COUNT(DISTINCT CASE WHEN [amount] < 1500 THEN AcctNo_PKey END)

Which you can see in action in this minimal sqlfiddle example

like image 185
Dan Avatar answered Nov 04 '22 21:11

Dan