我正在使用SQL Server 2008,我遇到了这个问题。
我有一个包含工作字段,日期字段和成本字段的表。日期字段包含在特定作业上完成工作的日期,而成本字段包含在该日期花费的金额(单个作业可以在几天内完成工作)
我想创建一个select语句,以便获得在不同列中打开作业的0-7days和8-30days之间花费的总和。
我试过了:
select a.[Job No_], DATEDIFF(day, MIN(b.[Posting Date]), a.[Ending Date]) as [WIP Age],
SUM(b.[Total Cost])[Total WIP cost]
[0 - 7 days]=case
when (DATEDIFF(day, MIN(b.[Posting Date]), a.[Ending Date]) between 1 and 7) then
SUM(b.[Total Cost])
else 0
end,
[8 - 30 days]=case
when (DATEDIFF(day, MIN(b.[Posting Date]), a.[Ending Date]) between 8 and 30) then
SUM(b.[Total Cost])
else 0
end,
[> 30 days]=case
when (DATEDIFF(day, MIN(b.[Posting Date]), a.[Ending Date]) > 30) then
SUM(b.[Total Cost])
else 0
end
from [Job]a
right join [Job Ledger Entry]b
on b.[Job No_] = a.[No_]
group by a.[No_]
显示与此类似的结果:
Job No_ WIP Age Total WIP cost 0 - 7 days 8 - 30 days > 30 days
0001 40 9526.18 0 0 9526.18
0002 27 1178.49 0 1178.49 0
0003 3 2838.94 2838.94 0 0
这不是我想要的,我希望所有费用分别在0 - 7天,8 - 30天和> 30天之间。
答案 0 :(得分:0)
以下可能会做得更好:
SELECT
a.[Job No_],
[WIP Age] = DATEDIFF(day, MIN(b.[Posting Date]), MAX(a.[Ending Date])),
[Total WIP cost] = SUM(b.[Total Cost]),
[0 - 7 days] = SUM(CASE
WHEN (DATEDIFF(DAY, b.[Posting Date], a.[Ending Date]) BETWEEN 1 AND 7)
THEN SUM(b.[Total Cost])
END),
[8 - 30 days] = SUM(CASE
WHEN (DATEDIFF(DAY, b.[Posting Date], a.[Ending Date]) BETWEEN 8 AND 30)
THEN b.[Total Cost]
END),
[> 30 days] = SUM(CASE
WHEN (DATEDIFF(day, b.[Posting Date], a.[Ending Date]) > 30)
THEN b.[Total Cost]
END)
FROM [Job] a
RIGHT JOIN [Job Ledger Entry] b ON b.[Job No_] = a.[No_]
GROUP BY a.[No_]
说明:我将所有CASE表达式放在相应的SUM中。我还在第一个DATEDIFF中将MAX()应用于a.[Ending Date]
,因为使用该列而不进行聚合似乎是错误的。