在同一个select语句中选择别名

时间:2016-05-17 20:03:20

标签: sql select alias

    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的新手。我相信我需要的是一个子查询,但我不确定如何正确格式化

谢谢

2 个答案:

答案 0 :(得分:0)

  1. IF用于程序流程,而不是表达式
  2. 您无法在其他列中重复使用别名
  3. 比较数字结果时,不要在引号
  4. 中包围常量值

    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