我是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
答案 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
替换了第一个条件 - 更简单来阅读。答案 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
查询中创建并显示别名。