我有一个具有此架构的Ledger 表:
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;
您不需要为要实现的逻辑进行日期转换。
关于mysql - 跨子查询的 SQL SUM(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54241101/