到目前为止,我写了这篇文章:
SELECT
Query,
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2013-01-01' THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN SearchDate >= '2013-01-01' and SearchDate < '2014-01-01' THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
它查看表格中的查询(搜索)术语,并计算每个在给定日期范围内出现的次数(在本例中为今年和最后一次)。
在结果中,我想只显示那些出现100次或更多次的内容。现在它显示了所有。
Query Year2012 Year2013
beavers 90 87
hair 4 14
如果最好的方法不涉及CASE WHEN,请告诉我!初学者。
答案 0 :(得分:2)
使用其他having
子句
SELECT
Query,
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2013-01-01' THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN SearchDate >= '2013-01-01' and SearchDate < '2014-01-01' THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
having
SUM(CASE WHEN SearchDate >= '2012-01-01' and SearchDate < '2014-01-01'
THEN 1
ELSE 0
END) >= 100
答案 1 :(得分:1)
我认为这更清晰,更容易维护:
SELECT
Query,
SUM(CASE WHEN year(SearchDate) = 2012 THEN 1 ELSE 0 END) as Year2012,
SUM(CASE WHEN year(SearchDate) = 2013 THEN 1 ELSE 0 END) as Year2013
FROM dbo.tblSearch WITH (NOLOCK)
WHERE DomainProjectID=13
GROUP BY Query
having
SUM(CASE WHEN year(SearchDate) in (2012, 2013) THEN 1 ELSE 0 END)
>= 100