为什么我的减法结果不正确?

时间:2016-04-27 20:36:24

标签: sql-server tsql ssms azure-sql-database

select sum(l.coins) - sum(t.coins) as total
from luxx_getaway_2016_coins l
join thrive_rewards_redeemed t
on l.consid = t.guideid
where l.consid = 24969 and t.harvestyear = 1516

大家好。我试图使用上面的查询获取更新的总数。我遇到的问题是这些总和的总和远高于应有的总和。我不确定我做错了什么。我们正在使用Azure SQL数据库,并且我使用RazorSQL和SSMS 2012以相同的结果运行此查询。任何帮助表示赞赏。请随时要求澄清。

1 个答案:

答案 0 :(得分:0)

解决重复问题的简单方法:

Select
    (select sum(l.coins)
    from luxx_getaway_2016_coins l
    where l.consid = 24969)

-
    (select sum(t.coins)
    from thrive_rewards_redeemed t
    where t.guideid = 24969 
        and t.harvestyear = 1516)

对于更一般的情况:

; With A as (select consid, sum(l.coins) as TotA
    from luxx_getaway_2016_coins l
    group by consid)
, B as (select guideid, sum(t.coins) as TotB
    from thrive_rewards_redeemed t
    where t.harvestyear = 1516
    group by guideID)

Select a.consid, TotA - TotB as Total 
from A
inner join B
on a.Consid = b.GuideID