我有这样的 sql 查询,其中输入是 @year = 2017
而列格式为 '2017-01-01 05:02:45.000'
。我想调整这个查询,因为它的执行时间很长。
DECLARE @Device_List VARCHAR(500) = 'MKV005, MKV007, NWTN01, NWTN03, QUEEN02, MKV009';
DECLARE @YEAR VARCHAR(20) = '2017'
SELECT MONTH(deduction_timestamp) as [Month],
ISNULL(sum(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog]
WHERE bus_id in (select * from fnSplit(@Device_List, ','))
and YEAR(deduction_timestamp) = ISNULL(@Year, YEAR(deduction_timestamp))
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
并且愿意这样做
SELECT MONTH(deduction_timestamp) as [Month],
ISNULL(sum(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog]
WHERE bus_id in (select * from fnSplit(@Device_List, ','))
and (deduction_timestamp) >= '@year-01-01 00:00:00' and
(deduction_timestamp) < '@year(plus one year)-01-01 00:00:00'
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]
但目前由于错误无法正常工作
Conversion failed when converting date and/or time from character string.
你们能帮帮我吗?真的很感激。谢谢
最佳答案
您需要将年份变量与字符串的其余部分连接起来,不能将其嵌入到字符串中。
deduction_timestamp < CONVERT(DATETIME, @year + '-01-01 00:00:00')
关于mysql - 按年调优sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291629/