[英]Select alias in same select statement
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的新手。 我相信这里我需要一个子查询,但是我不确定如何正确设置其格式
谢谢
IF
用于程序流,不是表达式 尝试
CASE WHEN DATEDIFF(day,getdate(),i.DiscDate) between 20 and 11
THEN sum(Dcount)
ELSE 0
END as YelDisc
您可以执行子查询以重用别名,但是对于这样一个相对简单的表达式,结果集中的列数可能不值得。
您不能在同一查询中引用别名,但是可以执行以下操作:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.