选择不同的WHERE条件

时间:2012-07-31 17:37:58

标签: sql select where

我想运行这样的选择。

SELECT
        COUNT(*) WHERE switch=0 AND detail=1 AS zeroone
    AND
        COUNT(*) WHERE switch=0 AND detail=2 AS zerotwo
    AND
        COUNT(*) WHERE switch=1 AND detail=1 AS oneone
    AND 
        COUNT(*) WHERE swithc=1 AND detail=2 AS onetwo
  FROM tablename

有办法做到这一点吗?

5 个答案:

答案 0 :(得分:4)

SELECT
    sum(switch=0 AND detail=1) AS zeroone,
    sum(switch=0 AND detail=2) AS zerotwo,
    sum(switch=1 AND detail=1) AS oneone,
    sum(switch=1 AND detail=2) AS onetwo
FROM tablename

答案 1 :(得分:4)

您可以在CASE中使用SELECT声明来获取结果:

SELECT SUM(case when switch=0 AND detail=1 then 1 else 0 end) as zeroone
    , SUM(case when switch=0 AND detail=2 then 1 else 0 end) as zerotwo
    , SUM(case when switch=1 AND detail=1 then 1 else 0 end) as oneone
    , SUM(case when switch=1 AND detail=2 then 1 else 0 end) as onetw
FROM tablename

答案 2 :(得分:1)

SELECT SUM(CASE WHEN switch = 0 and detail = 1 THEN 1 ELSE NULL END) AS zeroone
     , ...
FROM TableName

答案 3 :(得分:0)

目前尚不清楚你想要什么。

我想你想要一个select,它返回一行,有4列:

SELECT
COUNT(*) WHERE switch=0 AND detail=1 AS zeroone,
COUNT(*) WHERE switch=0 AND detail=2 AS zerotwo,
COUNT(*) WHERE switch=1 AND detail=1 AS oneone,
COUNT(*) WHERE swithc=1 AND detail=2 AS onetwo
FROM tablename

答案 4 :(得分:0)

为什么不用这个?

SELECT COUNT(*) 
  FROM tablename
 GROUP BY switch, detail