【问题标题】:select case when not working as expected未按预期工作时选择案例
【发布时间】:2012-07-29 18:57:30
【问题描述】:

我正在尝试了解它是如何工作的,但还无法弄清楚。

我做了这个简单的方法来测试 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

任何帮助将不胜感激! 谢谢, 狮子座

【问题讨论】:

    标签: mysql sql select case


    【解决方案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】:

    没有GROUP BY 的聚合函数COUNT() 将返回表中未被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
    

    【讨论】:

    • 感谢迈克尔的快速回答!
    【解决方案3】:

    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
    

    【讨论】:

    • 谢谢!我以为我像在 oracle 数据库中一样编写它......它有效!再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多