简体   繁体   中英

how to have a where clause in an aggregate function SQL Server

OK, I have a table that looks like this:

ID   AMOUNT      PAID
1    50.00       Y
2    100.00      N
3    200.00      Y

And I want to see something like:

Total     Due Paid
350.00    1   2

So my SQL would look like (in my head...it doesnt work that way, which is why I'm here )

select sum(amount)
,count(paid where paid='y') as due
,count(paid where paid='n') as paid 
from sometable where something=somethingelse
select sum(amount) as total, 
       sum(case paid when 'N' then 1 else 0 end) as due, 
       sum(case paid when 'Y' then 1 else 0 end) as paid
from sometable where something=somethingelse

One more option

SELECT SUM(AMOUNT) AS Total,
       COUNT(CASE WHEN PAID = 'Y' THEN PAID END) AS Paid,
       COUNT(CASE WHEN PAID = 'N' THEN PAID END) AS Due
FROM sometable
WHERE something = somethingelse

Demo om SQLFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM