2 T-SQL queries that should be the same are not

时间:2015-07-28 17:02:46

标签: tsql

I have the 2 below queries that should produce the same result as far as I can tell but they are actually producing vastly different numbers. Why is "Between" dates not the same as specifying the month and year of those dates? What could be causing this?

SELECT [Account]
    , SUM([Amount]) AS [Amount]
FROM [Table]
WHERE [Account] = 'Specific Account'
AND Month([Date]) = 5
AND Year([Date]) = 2015
GROUP BY [Account]

Sum Result: -1,500,000

SELECT [Account]
    , SUM([Amount]) AS [Amount]
FROM [Table]
WHERE [Account] = 'Specific Account'
AND [Date] BETWEEN '2015-05-01' AND '2015-05-31'
GROUP BY [Account]

Sum Result: 350,000

I need the first one to be correct because I need to group the results by Month and Year, which would be cumbersome using the second query.

Query that I need ultimately:

SELECT [Account]
    , Month([Date]) AS [Month]
    , Year([Date]) AS [Year]
    , SUM([Amount]) AS [Amount]
FROM [Table]
GROUP BY [Account]
    , Month([Date])
    , Year([Date]) 

2 个答案:

答案 0 :(得分:4)

 [Date] BETWEEN '2015-05-01' AND '2015-05-31'

只会包含31日时间组件为午夜的行,而忽略当天剩余的时间。

您应该忘记BETWEEN,因为没有有效的字符串文字可以放在右侧,可以正常使用datetimesmalldatetimedatetime2(0)..datetime2(7)并使用

WHERE [Date] >= '2015-05-01' AND [Date] < '2015-06-01'

答案 1 :(得分:0)

Try below for your first case, where you are getting more rows.

AND (Month([Date]) = 5 AND Year([Date]) = 2015)

instead of

AND Month([Date]) = 5 AND Year([Date]) = 2015

==Update==

I would suggest to use CONVERT function. And you should revise your query like below

CONVERT(varchar(10),DATE_COLUMN,112) between '20150501' and '20150531'