2

好的,我有一个如下所示的表:

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

我想看到类似的东西:

Total     Due Paid
350.00    1   2

所以我的 SQL 看起来像(在我的脑海中......它不是那样工作的,这就是我在这里的原因)

select sum(amount)
,count(paid where paid='y') as due
,count(paid where paid='n') as paid 
from sometable where something=somethingelse
4

2 回答 2

5
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
于 2012-12-04T14:50:24.847 回答
1

另一种选择

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

演示 om SQLFiddle

于 2012-12-04T20:44:47.630 回答