mysql - 按年调优sql

标签 mysql sql sql-server

我有这样的 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/

相关文章:

php - SQL 语法错误/无效查询 - WAMP、phpMyAdmin

c# - 从 C# 控制台应用程序查询网站数据库

mysql - mysql 触发器出了什么问题

mysql - 添加子查询

sql-server - 如何解决此 visual studio 查询错误?

MySQL CrossTab 结果包含非不同列

mysql - Java调度线程杀死数据库

sql - 使 PostgreSQL 查询更干

SQL递归索引查找查询

mysql - 关于从 SQL Server 更改为 MySql 的建议