0

到目前为止,我已经写了这个:

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,请告诉我!初学者在这里。

4

2 回答 2

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 
于 2013-11-05T17:24:13.987 回答
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 
于 2013-11-05T17:44:50.820 回答