繁体   English   中英

在同一条选择语句中选择别名

[英]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的新手。 我相信这里我需要一个子查询,但是我不确定如何正确设置其格式

谢谢

  1. IF用于程序流,不是表达式
  2. 您不能在另一列中重复使用别名
  3. 比较数值结果时,请不要在引号中包含常量值

尝试

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM