根据条件对同一列计数两次

时间:2020-06-16 08:32:08

标签: sql sql-server

如果Account_Fkey不为空,我有以下查询将“金额”字段计算为“已使用”

select Amount as amount2, Count(Amount) as CountUsed  from tblGiftCards
where Account_Fkey is not null
group by Amount 

结果:

amount2 CountUsed   
25      3
50      10
100     5

我想将金额计算为在帐户fkey为null的同一查询中未使用的金额。因此,结果将是:

amount2 CountUsed CountUnused   
25      3         1
50      10        0
100     5         2

谢谢

3 个答案:

答案 0 :(得分:2)

您可以使用条件聚合

select Amount as amount2
    , sum( case when  Account_Fkey is not null 
            and Amount is not null then 1 else 0 end)  CountUsed  
    , sum( case when  Account_Fkey is null 
            and Amount is not null then 1 else 0 end)  CountNotUsed  
    from tblGiftCards
group by Amount 

答案 1 :(得分:1)

尝试

select tab.amount2 , CountUsed , CountUnUsed   from 
(select Amount as amount2, Count(Amount) as CountUsed  from tblGiftCards
where Account_Fkey is not null
group by Amount 
) tab, 
(select Amount as amount2, Count(Amount) as CountUnUsed  from tblGiftCards
where Account_Fkey is null
group by Amount 
)tab2
where tab.amount2 = tab2.amount2

答案 2 :(得分:1)

我将简化逻辑并将其表示为:

select Amount as amount2, count(Account_Fkey) as CountUsed,
       (count(*) - count(Account_Fkey)) as CountNotUsed
from tblGiftCards
where Amount is not null
group by Amount