子查询中的SQL SUM()

秃鹰51

我有一个带有此模式分类帐表:

LedgerId    (int,not null)
Timestamp   (datetime, not null)
CostCenter  (int, not null)
Payee       (varchar(50), not null)
Type        (varchar(3),not null)
Category    (varchar(24), not null)
Amount      (decimal(8,2) not null)
Tag         (varchar(30),null)
Memo        (varchar(150), null)

在这里记录小型企业的费用交易。

年终时,对于任何收到600美元以上的承包商,我必须向IRS发出1099表。我运行以下查询(感谢StackExchange!)以获取此查询:

SELECT Payee as Name, SUM(Amount)as Total FROM Ledger 
where (convert(date,timestamp) < convert(date,'2019-01-01')) 
and (convert(date,timestamp) > convert(date,'2017-12-31')) 
and category like '%Contract%' 
group by Payee having SUM(amount) > 600 
order by Payee

太好了,这给了我每个承包商的清单以及2018年的总额。

我现在想要的是一个查询,该查询将提供我在2018年为这些承包商花费的总金额(也用于IRS,表格1096)。如果我将此查询用作获得此总数的子查询,则会出错。我该如何总计所有承包商费用?

戈登·利诺夫

您是说这行不通吗?

select sum(total)
from (select Payee as Name, SUM(Amount) as Total 
      from Ledger 
      where timestamp < '2019-01-01' and
            timestamp >= '2018-01-01' and
            category like '%Contract%' 
      group by Payee
      having sum(amount) > 600 
     ) l;

您不需要为要实现的逻辑进行日期转换。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章