0

快一个,

我有一张桌子,结构如下

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

4 回答 4

3

你可以这样做:

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

这将返回两行:

taken  count
0      2
1      2

每个计数对应taken于看到该特定值的次数。

于 2012-06-13T15:23:11.190 回答
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
于 2012-06-13T15:24:11.547 回答
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
于 2012-06-13T15:24:46.803 回答
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
        ;
于 2012-06-13T15:35:37.827 回答