不按预期工作时选择案例

时间:2012-07-31 22:11:44

标签: mysql sql select case

我正在试图了解它是如何工作的,但还是无法解决它。

我已经用这个简单的uery来测试case-when-then-end子句......

  SELECT case when quantity > 3
              then count(*) end the_count_a,
         case when quantity <= 3
              then count(*) end the_count_b
    FROM STOCK

我的库存表有30个不同数量的商品,只有10个商品的数量超过3但是这总是返回30 ....为什么? 我认为它应该返回两列值:10和20

任何帮助将不胜感激! 谢谢, 利奥

3 个答案:

答案 0 :(得分:4)

count(*)的值表示所有记录(在当前组中)的计数,无论它放在何处。如果要计算与条件匹配的记录,则需要反转case语句:

select count(case when quantity > 3 then 1 end) the_count_a,
       count(case when quantity <= 3 then 1 end) the_count_b
  from stock

答案 1 :(得分:1)

SELECT 
       count(case when quantity > 3 then 1 else null end) end the_count_a,
       count(case when quantity <= 3 then 1 else null end) end the_count_b
FROM STOCK

答案 2 :(得分:0)

缺少COUNT()的聚合函数GROUP BY将返回表中尚未被WHERE子句过滤的所有行。在您的情况下,您实际需要的是两个子选择或UNION,具体取决于您是否需要列或行:

/* Return columns with subselects */
SELECT
  (SELECT COUNT(*) FROM STOCK WHERE quantity > 3) AS the_count_a
  (SELECT COUNT(*) FROM STOCK WHERE quantity <= 3) AS the_count_b

MySQL对于FROM子句的存在是宽容的,因此可以从外部查询中省略它。

/* Return rows instead of columns with UNION */
SELECT 
  COUNT(*) AS the_count,
  'the_count_a'
FROM STOCK WHERE quantity > 3
UNION ALL
SELECT 
  COUNT(*) AS the_count,
  'the_count_b'
FROM STOCK WHERE quantity <= 30