我有两列带有日期值,我想过滤它们以仅在两列具有相似值时才能看到结果。 我在“哪里”部分有两个问题。谁能帮我这个? 1)如何比较这两个列之间的值与日期值? 2)如果我使用的是varchar值而不是日期,该如何比较两个值?
SELECT [USERNAME], count(*) AS [NumberOfHappening], min([date1]) AS [FirstDate], max([date2]) AS [SecondDate]
FROM TableMain
WHERE CAST([FirstDate] AS DATE) = CAST([SecondDate] AS DATE)
GROUP BY [USERNAME]
ORDER BY 'NumberOfHappening' DESC
谢谢。
答案 0 :(得分:1)
是否正确键入了原始日期值,或者您是否将日期/时间值存储在字符串列中?如果是这样,您应该真正更改此...
如果我正确理解了这一点,则您想查找date1
和date2
在同一天的记录。将DATETIME
投射到DATE
会摆脱时间部分。
您可以使用CTE直接使用列别名
;WITH cte AS
(
SELECT [USERNAME], count(*) AS [NumberOfHappening], min([date1]) AS [FirstDate], max([date2]) AS [SecondDate]
FROM TableMain
GROUP BY [USERNAME]
)
SELECT *
FROM cte
WHERE CAST([FirstDate] AS DATE) = CAST([SecondDate] AS DATE)
ORDER BY NumberOfHappening DESC;