一个select语句中的不同条件

时间:2012-06-26 12:58:19

标签: sql-server-2008 select where-clause

你怎么能Select两列并让每一列测试它自己的条件而不是另一列?

假设我选择Count表格中的每条记录。在一栏中,我想要本周的每一条记录,而在第二栏中,我想要从年初开始的所有记录。

我有两个条件,但它们各自适用于特定列:

        WHERE date BETWEEN @Monday AND @SUNDAY  /* Weekly */
        WHERE date >= @JanuaryFirst             /* Annual */

但不能只是这样说,因为我只会在两个专栏中获得本周的记录。我以为我可以使用IF条件,但我认为我不能简单地说“如果你是A列测试,如果没有测试第二个”。

enter image description here

3 个答案:

答案 0 :(得分:3)

这是一个不会产生多次扫描的版本:

select vehicule,
  weekly = SUM(CASE WHEN date BETWEEN @Monday AND @SUNDAY THEN 1 ELSE 0 END),
  annual = SUM(CASE WHEN date >= @JanuaryFirst THEN 1 ELSE 0 END)
from dbo.tablename AS t
GROUP BY vehicule;

或者你也可以尝试稍微冗长的一点:

select vehicule,
  weekly = COUNT(CASE WHEN date BETWEEN @Monday AND @SUNDAY THEN 1 END),
  annual = COUNT(CASE WHEN date >= @JanuaryFirst THEN 1 END)
from dbo.tablename AS t
GROUP BY vehicule;

答案 1 :(得分:2)

如果您想避免使用子查询,可以使用:

select vehicule,
sum(case when date BETWEEN @Monday AND @SUNDAY then 1 else 0 end)  as 'Weekly',
sum(case when date >= @JanuaryFirst then 1 else 0 end)  as 'Annual' 
group by vehicule

答案 2 :(得分:1)

使用INNER SELECTS,如下所示:

select vehicule,
       (select count(*) from tablename t1 where t1.vehicule = t.vehicule and date BETWEEN @Monday AND @SUNDAY) as 'Weekly',
       (select count(*) from tablename t1 where t1.vehicule = t.vehicule and date >= @JanuaryFirst) as 'Annual'
from tablename t