我是Mssql服务器的新手,我正在尝试将Mysql查询迁移到Mssql上,因为该查询遇到了问题。
查询是:
SELECT converT(datetime,SWITCHOFFSET(converT(datetimeoffset,created), 'America/New_York')),
SUM(case when channel='FACEBOOK' then 1 else 0 end) AS Messenger,
SUM(case when channel='EMAIL' then 1 else 0 end) AS Email,
SUM(case when channel='ECHO' then 1 else 0 end) AS Echo
FROM Conversation
WHERE tenant_id=2 AND createdBy_id in(3)
AND created >= '2018-11-01 06:00:01'
GROUP BY year(created), month(created), DATEPART(week,created),day(created)
ORDER BY created ASC;
我面临的错误是:
在选择列表中,列Conversation.created
无效,因为它没有包含在聚合函数或GROUP BY
子句中。
当我尝试在没有聚合函数的情况下执行查询时,converT
和sum
的组合无法正常工作。有人可以帮我吗?
预先感谢
答案 0 :(得分:0)
当您已经将其他字段分组并且要在converT(datetime,SWITCHOFFSET(converT(datetimeoffset,created)
中显示此结果时,有必要在Group By
中添加此Group By
:
SELECT
converT(datetime,SWITCHOFFSET(converT(datetimeoffset,created), 'America/New_York')),
SUM(case when channel='FACEBOOK' then 1 else 0 end) AS Messenger,
SUM(case when channel='EMAIL' then 1 else 0 end) AS Email,
SUM(case when channel='ECHO' then 1 else 0 end) AS Echo
FROM Conversation
WHERE tenant_id=2 AND createdBy_id in(3)
AND created >= '2018-11-01 06:00:01'
GROUP BY converT(datetime,SWITCHOFFSET(converT(datetimeoffset,created), year(created),
month(created), DATEPART(week,created),day(created)
ORDER BY created ASC;
此错误表示您在SUM
字段中有channel
-一行,但是SQL Server
也有许多带有created
列的行,并且它不知道应该选择哪一行。