i.Notes, SUM(l.Discount) AS Dcount, i.DiscDate, i.DueDate, i.UIMth, i.UISeq, poj.Job, poj.Description, i.UniqueAttchID, i.ReviewerGroup AS RevGrp, SUM(l.GrossAmt)
AS GrossAmt, v.PayTerms, dbo.HQPT.DiscRate, i.InvTotal, DATEDIFF(day,getdate(),i.DiscDate) AS DiscDays,
--Trying to use the DiscDays and Dcount here
if DiscDays, between '20' and '11' THEN sum(Dcount) as YelDisc
我希望有人可以帮助我。我是T-SQL的新手。我相信我需要的是一个子查询,但我不确定如何正确格式化
谢谢
答案 0 :(得分:0)
IF
用于程序流程,而不是表达式试
CASE WHEN DATEDIFF(day,getdate(),i.DiscDate) between 20 and 11
THEN sum(Dcount)
ELSE 0
END as YelDisc
你可以做一个子查询来重用别名,但是对于这样一个相对简单的表达式以及结果集中的列数,它可能不值得。
答案 1 :(得分:0)
您无法在同一查询中引用别名,但您可以执行以下操作:
select
i.Notes,
SUM(l.Discount) AS Dcount,
i.DiscDate,
i.DueDate,
i.UIMth,
i.UISeq,
poj.Job,
poj.Description,
i.UniqueAttchID,
i.ReviewerGroup AS RevGrp,
SUM(l.GrossAmt) AS GrossAmt,
v.PayTerms,
dbo.HQPT.DiscRate,
i.InvTotal,
DATEDIFF(day,getdate(),i.DiscDate) AS DiscDays,
--Trying to use the DiscDays and Dcount here
case
when DATEDIFF(day,getdate(),i.DiscDate) between '11' and '20' THEN sum(Dcount)
when DATEDIFF(day,getdate(),i.DiscDate) between '20' and '40' THEN sum(Dcount)/2
else 0 -- this is the default case that doesn't match your cases, it could return NULL
end as YelDisc