SQL日期范围查询:月份到月份OK但是整年不正确的结果

时间:2017-12-01 10:43:14

标签: sql sql-server

我在下面有一个查询,它会在逐月执行时返回正确的结果。即1jan -31st jan,2月2日 - 28日,3月1日至3月31日等等。

但是当我设置historydate> =' 2017-01-01'捕获全年,它返回完全错误的结果。有任何想法吗?我在mssql上

SELECT DISTINCT
       cl.id AS id, cl.[KEY] AS issuekey,
       MAX(historyDate) AS releaseDate,
       m.issueType,
       m.priority
FROM d_jira_changelog cl
     JOIN d_jira_changelog_items ci ON ci.historyId = cl.historyId
     JOIN d_jira_main m ON m.id = cl.id
WHERE(ci.changeitemfrom = 'Phase1'
      AND ci.changeItemTo = 'Phase2')
     AND changeItemField = 'status'
     AND m.projectkey IN('ABC', 'CBA', 'XYZ', 'YOYO')
     AND historydate >= '2017-01-01'
GROUP BY cl."id", cl."key", m.issueType, m.priority;

1 个答案:

答案 0 :(得分:0)

问题似乎是在哪里条款如果列历史日期是日期时间那么你肯定不会根据这个WHERE条款得到任何记录 historydate> ='2017-01-01'

SELECT DISTINCT
       cl.id AS id, cl.[KEY] AS issuekey,
       MAX(historyDate) AS releaseDate,
       m.issueType,
       m.priority
FROM d_jira_changelog cl
     JOIN d_jira_changelog_items ci ON ci.historyId = cl.historyId
     JOIN d_jira_main m ON m.id = cl.id
WHERE(ci.changeitemfrom = 'Phase1'
      AND ci.changeItemTo = 'Phase2')
     AND changeItemField = 'status'
     AND m.projectkey IN('ABC', 'CBA', 'XYZ', 'YOYO')
     CONVERT(NVARCHAR,historydate,111) >= CONVERT(NVARCHAR,'2017-01-01',111) 
GROUP BY cl."id", cl."key", m.issueType, m.priority;