按年调整sql

时间:2018-03-15 04:30:54

标签: 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]

但是目前由于错误而无法正常工作

  

从字符转换日期和/或时间时转换失败   字符串。

你能帮助我吗?真的很感激。感谢

3 个答案:

答案 0 :(得分:3)

您需要将year变量与字符串的其余部分连接起来,不能将其嵌入到字符串中。

deduction_timestamp < CONVERT(DATETIME, @year + '-01-01 00:00:00')

答案 1 :(得分:2)

我会将您的第一个查询重新编写为

DECLARE @Device_List VARCHAR(500) = 'MKV005, MKV007, NWTN01, NWTN03, QUEEN02, MKV009';

DECLARE @YEAR VARCHAR(20) = '2017'

SELECT MONTH(deduction_timestamp) as [Month],
       COALESCE(SUM(fare_deduction), 0) AS total_fare_deduction
FROM [dbfastsprocess].[dbo].[vClosingTransitLog] c
CROSS APPLY (
      select * from fnSplit(@Device_List, ',')
      where bus_id  = c.bus_id 
)
WHERE (@Year IS NOT NULL AND YEAR(c.deduction_timestamp) = @Year) OR
      (@Year IS NULL)
GROUP BY MONTH(deduction_timestamp)
ORDER BY [Month]

使用ANSI SQL Standard COALESCE()函数代替ISNULL()

答案 2 :(得分:0)

May be you want the see the output for year 2017 or later then I do not understand why are you using (deduction_timestamp) < '@year-01-01 00:00:00'
Please check this query:
     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) >= @year
            GROUP BY MONTH(deduction_timestamp)
            ORDER BY [Month]