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
I am hoping someone can help me here. I am very new to T-SQL. I believe what I need here is a sub Query but I'm not sure how to format it correctly
Thank you
IF
is for program flow, not an expression try
CASE WHEN DATEDIFF(day,getdate(),i.DiscDate) between 20 and 11
THEN sum(Dcount)
ELSE 0
END as YelDisc
You could do a subquery to reuse the alias, but for such a relatively simple expression and with the number of columns in your result set it's probably not worth it.
You cannot reference an alias within the same query but what you could do is the following:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.