具有多个条件的SQL Count然后加入

时间:2012-06-13 15:19:40

标签: sql

快点,

我有一张桌子,结构如下

id  lid  taken
1   1    0
1   1    0
1   1    1
1   1    1
1   2    1

非常简单到目前为止?

我需要查询1的盖子中的拍摄/可用,这应该返回

taken  available
2      2

我知道我可以简单地做两个计数并加入它们,但有没有更熟练的方法来做这个而不是两个单独的查询?

我正在查看以下类型的格式,但我不能为我的生活让它在SQL中执行...

SELECT
   COUNT(case taken=1) AS taken, 
   COUNT(case taken=0) AS available FROM table
WHERE 
   lid=1

非常感谢你。

4 个答案:

答案 0 :(得分:3)

你可以这样做:

SELECT taken, COUNT(*) AS count
FROM table
WHERE lid = 1
GROUP BY taken

这将返回两行:

taken  count
0      2
1      2

每个计数对应于特定taken值的显示次数。

答案 1 :(得分:2)

你的查询是正确的只需要玩杂耍:

SELECT
   SUM(case taken WHEN 1 THEN 1 ELSE 0 END) AS taken, 
   SUM(case taken WHEN 1 THEN 0 ELSE 1 END) AS available FROM table
WHERE 
   lid=1

或者你可以这样做:

SELECT
   SUM(taken) AS taken, 
   COUNT(id) - SUM(taken) AS available 
FROM table
WHERE 
   lid=1

答案 2 :(得分:1)

SELECT
   SUM(case WHEN taken=1 THEN 1 ELSE 0 END) AS taken, 
   SUM(case WHEN taken=0 THEN 1 ELSE 0 END) AS available 
FROM table
WHERE lid=1

答案 3 :(得分:1)

CTE的奇怪应用:

WITH lid AS (
        SELECT DISTINCT lid FROM taken
        )
, tak AS (
        SELECT lid,taken , COUNT(*) AS cnt
        FROM taken t0
        GROUP BY lid,taken
        )
SELECT l.lid
, COALESCE(a0.cnt, 0) AS available
, COALESCE(a1.cnt, 0) AS taken
FROM lid l
LEFT JOIN tak a0 ON a0.lid=l.lid AND a0.taken = 0
LEFT JOIN tak a1 ON a1.lid=l.lid AND a1.taken = 1
WHERE l.lid=1
        ;