我正在努力将mysql查询转换为sql查询,但由于我收到错误,我对sql server没有太多了解,这里我已经发布了我的两个查询,有谁可以帮我解决这个问题查询,我收到错误
Each GROUP BY expression must contain at least one column that is not an outer reference.
Mysql Query(在mysql服务器中正常工作):
SELECT 'Ending Episodes' as display_name, MonthEnd as MonthStart, MonthEnd as MonthEnd, AVG(FullHHRG) as FullHHRG,
AVG(LUPAAdj) as LUPAAdj, AVG(OutlierAdd) as OutlierAdd, AVG(UpDownCode) as UpDownCode, AVG(Sequester) as Sequester,
AVG(NetHHRG) as NetHHRG, count(tb_Episode.id) as total
FROM tb_Episode
WHERE EpEnd is not null AND EpEnd >= '01-01-01' AND EpEnd < '01-01-01' AND tb_Episode.CustID = '27'
GROUP BY display_name, MonthEnd ORDER BY tb_Episode.MonthEnd asc
转换的SQL查询(获取错误)
SELECT 'EndingEpisodes' as display_name, MonthEnd as MonthStart, MonthEnd as MonthEnd, AVG(FullHHRG) as FullHHRG,
AVG(LUPAAdj) as LUPAAdj, AVG(OutlierAdd) as OutlierAdd, AVG(UpDownCode) as UpDownCode, AVG(Sequester) as Sequester,
AVG(NetHHRG) as NetHHRG, count(DISTINCT tb_Episode.id) as total
FROM tb_Episode
WHERE EpEnd is not null AND EpEnd >= '01-01-01' AND EpEnd < '01-01-01' AND CustID = '27'
GROUP BY MonthEnd,FullHHRG,LUPAAdj,OutlierAdd,UpDownCode,Sequester,NetHHRG
ORDER BY MonthEnd asc
答案 0 :(得分:3)
我认为您只需要monthend
中的group by
:
SELECT 'EndingEpisodes' as display_name, MonthEnd as MonthStart, MonthEnd as MonthEnd,
AVG(FullHHRG) as FullHHRG, AVG(LUPAAdj) as LUPAAdj, AVG(OutlierAdd) as OutlierAdd,
AVG(UpDownCode) as UpDownCode, AVG(Sequester) as Sequester,
AVG(NetHHRG) as NetHHRG, count(DISTINCT tb_Episode.id) as total
FROM tb_Episode
WHERE EpEnd is not null AND
EpEnd >= '01-01-01' AND
EpEnd < '01-01-01' AND
CustID = '27'
GROUP BY MonthEnd
ORDER BY MonthEnd asc;
SQL Server无法识别GROUP BY
子句中的列别名,因此问题是无法识别display_name
。这是一个常数,所以它没有什么区别。
另请注意,此版本将在MySQL中运行。您可能需要注意日期格式。
答案 1 :(得分:2)
我认为您的问题出在group by
SELECT
'EndingEpisodes' as display_name,
MonthEnd as MonthStart,
MonthEnd as MonthEnd,
AVG(FullHHRG) as FullHHRG,
AVG(LUPAAdj) as LUPAAdj,
AVG(OutlierAdd) as OutlierAdd,
AVG(UpDownCode) as UpDownCode,
AVG(Sequester) as Sequester,
AVG(NetHHRG) as NetHHRG,
count(DISTINCT tb_Episode.id) as total
FROM tb_Episode
WHERE EpEnd is not null AND EpEnd >= '01-01-01' AND EpEnd < '01-01-01' AND tb_Episode.CustID = '27'
GROUP BY MonthEnd
ORDER BY MonthEnd asc