获取错误SQL Server中的列名display_name无效

时间:2018-02-27 12:15:02

标签: sql sql-server

我是SQL Server新手,当我运行下面显示的查询时,我收到错误

  

列名称display_name

无效

任何人都可以帮助我吗?我该如何解决这个问题?

这是我的问题:

SELECT 
    'Nbr of RAPs' AS display_name, 
    MonthRap AS MonthStart, 
    COUNT(DISTINCT tb_Episode.id) AS total
FROM   
    tb_Episode
WHERE  
    (BranchID = '244' or BranchID = '242' or BranchID = '240' or BranchID = '243')
    AND RAPClaimDate IS NOT NULL
    AND RAPClaimDate >= '2017-01-01'
    AND RAPClaimDate < '2018-2-01'
    AND tb_Episode.CustID =  '27'
    AND tb_Episode.DTR >= 0
    AND tb_Episode.DTR <= '30'
    AND tb_Episode.PayorType =  'Medicare Traditional' 
GROUP BY 
    display_name, MonthRap
ORDER BY 
    tb_Episode.MonthRap ASC

2 个答案:

答案 0 :(得分:2)

它是一个常量,因此您不需要通过它进行聚合。出现此错误的原因是group by中不允许列别名。查询还有其他问题。我建议:

SELECT 'Nbr of RAPs' as display_name, 
       e.MonthRap as MonthStart, 
       count(*) as total
FROM tb_Episode e
WHERE e.BranchID IN (244, 242, 240, 243) AND
      e.RAPClaimDate is not null AND
      e.RAPClaimDate >= '2017-01-01' AND
      e.RAPClaimDate < '2018-02-01' AND
      e.tb_Episode.CustID = 27 AND
      e.tb_Episode.DTR >= 0 AND
      e.tb_Episode.DTR <= 30 AND
      e.tb_Episode.PayorType =  'Medicare Traditional' 
GROUP BY MonthRap
ORDER BY e.MonthRap asc;

注意:

  • 我删除了DISTINCT。据推测,id在表格中已经是唯一的。如果不是,请使用DISTINCT。但是,COUNT(DISTINCT)通常比COUNT(*)慢一点。
  • 我用IN替换了第一个条件 - 更简单来阅读。
  • 我删除了看起来像数字常量的单引号。如果您打算使用数字,请不要将数字转换为字符串。
  • 我将日期格式更改为YYYY-MM-DD。使用固定长度的格式,而不是在低编号的月份和日期内省略0。
  • 我还添加了一个表别名并限定了所有列名称。

答案 1 :(得分:1)

查询应为:

SELECT 'Nbr of RAPs' as display_name, 
       MonthRap as MonthStart, 
       count(DISTINCT tb_Episode.id) as total
FROM   tb_Episode
WHERE  (BranchID = '244' or BranchID = '242' or BranchID = '240' or BranchID = '243')
AND    RAPClaimDate is not null
AND    RAPClaimDate >= '2017-01-01'
AND    RAPClaimDate < '2018-2-01'
AND    tb_Episode.CustID =  '27'
AND    tb_Episode.DTR >= 0
AND    tb_Episode.DTR <= '30'
AND    tb_Episode.PayorType =  'Medicare Traditional' 
GROUP BY MonthRap
ORDER BY tb_Episode.MonthRap asc

请注意,group by删除了别名列'display_name'。您无法在group by中添加列名display_name,因为它已在SELECT查询中创建并显示别名。