有没有办法让这个查询不那么难看?我想避免代码重复,我不想为这么小的代码创建存储过程或函数
select
CB.CompanyName as ClientName,
Sum30 = (
select
sum(TotalAmount) as sum30
from
InvoiceBrowse
where
DATEDIFF(day, CreatedOn, @now) > @days_limit AND
DATEDIFF(day, CreatedOn, @now) <= 30 AND
ClientCompanyName = IB.ClientCompanyName
),
Sum60 = (
select
sum(TotalAmount) as sum30
from
InvoiceBrowse
where
DATEDIFF(day, CreatedOn, @now) > @days_limit AND
DATEDIFF(day, CreatedOn, @now) <= 60 AND
ClientCompanyName = IB.ClientCompanyName
),
Sum90 = (
select
sum(TotalAmount) as sum30
from
InvoiceBrowse
where
DATEDIFF(day, CreatedOn, @now) > @days_limit AND
DATEDIFF(day, CreatedOn, @now) <= 90 AND
ClientCompanyName = IB.ClientCompanyName
)
from
InvoiceBrowse IB
一些解释:我有发票的表格,想要计算每家公司的发票金额30 \ 60 \ 90天。
答案 0 :(得分:3)
看起来你在你的例子中错过了一个表..但是这样的事情可能有效。
SELECT ClientCompanyName AS ClientName,
SUM(CASE WHEN DATEDIFF(day,CreatedOn,@now) <= 30 THEN TotalAmount END) AS Sum30,
SUM(CASE WHEN DATEDIFF(day,CreatedOn,@now) <= 60 THEN TotalAmount END) AS Sum60,
SUM(CASE WHEN DATEDIFF(day,CreatedOn,@now) <= 90 THEN TotalAmount END) AS Sum90
FROM InvoiceBrowse
WHERE CreatedOn < DATEADD(DAY, -@days_limit, @now)
GROUP BY ClientCompanyName