简体   繁体   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  

I am hoping someone can help me here. 我希望有人可以在这里为我提供帮助。 I am very new to T-SQL. 我是T-SQL的新手。 I believe what I need here is a sub Query but I'm not sure how to format it correctly 我相信这里我需要一个子查询,但是我不确定如何正确设置其格式

Thank you 谢谢

  1. IF is for program flow, not an expression IF用于程序流,不是表达式
  2. You can't reuse an alias in another column 您不能在另一列中重复使用别名
  3. When comparing numeric results do not surround constant values in quotes 比较数值结果时,请不要在引号中包含常量值

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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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