我们有以下查询在MSSQL中完美运行但无法在MySQL中运行:
select CONVERT(datetime, dateVal) as DateOccurred, itemID, COUNT(*) as Hits from (
select itemID, CONVERT(datetime, DateClickUTC) as dateVal
from tb_items
where DateClickUTC >= '2008-06-03 22:00:28.893' and DateClickUTC <= '2013-06-03 22:00:28.893'
group by CONVERT(datetime, DateClickUTC), UserID, itemID) as a
group by a.dateVal, itemID
我们从MySQL得到的错误说:
语法错误,意外IDENT_QUOTED
第一行的dateVal变量发生此错误:&#34;选择CONVERT(datetime, dateVal )。&#34;
如果我们删除第一个CONVERT,那么错误就会移到下一行的下一个CONVERT。所以,很明显,我们的日期时间转换似乎有误。不知道我们做错了什么,有什么想法吗?谢谢大家。
答案 0 :(得分:1)
我更喜欢使用CAST
,但正如其他人所说,你需要在字段之后指定类型:
convert(DateClickUTC,datetime)
以下是使用CAST
的工作示例:
select a.dateVal as DateOccurred, itemID, COUNT(*) as Hits
from (
select itemID, cast(DateClickUTC as datetime) as dateVal
from tb_items
where DateClickUTC >= '2008-06-03 22:00:28.893' and DateClickUTC <= '2013-06-03 22:00:28.893'
group by cast(DateClickUTC as datetime), UserID, itemID
) as a
group by a.dateVal, itemID
顺便说一句 - 在这种情况下你实际上不需要子查询 - 这也应该有效:
select cast(DateClickUTC as datetime) as DateOccurred,
itemID,
COUNT(*) as Hits
from tb_items
where DateClickUTC >= '2008-06-03 22:00:28.893' and DateClickUTC <= '2013-06-03 22:00:28.893'
group by cast(DateClickUTC as datetime), itemID