【问题标题】:MySQL multiple count by one queryMySQL 一次查询多次计数
【发布时间】:2020-09-16 12:36:08
【问题描述】:

我试着统计每个月卖出了多少,然后得到一个数组。

$q = SELECT COUNT(id) AS January FROM tableName WHERE status='sold' AND month = '1'
UNION 
SELECT COUNT(id) AS February FROM tableName WHERE status='sold' AND month = '2'

$row = mysqli_fetch_array(mysqli_query($connection, $q));

print_r($row);

UNION 不起作用,当我尝试 print_r(array) 时,我得到了结果

[Jenuary] => 200

如何在两个月内获得一个数组?

我想要结果:

[January] => 200,
[February] => 221

【问题讨论】:

    标签: php mysql count pivot where-clause


    【解决方案1】:

    您可以尝试此查询以获得所需的确切结果。

    select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
    from tablename
    where status = 'sold'
    group by month
    

    仅适用于特定月份

     select MONTHNAME(STR_TO_DATE(month, '%m')) as month, count(*) cnt
        from tablename
        where status = 'sold' and month in(1, 2)
        group by month
    

    【讨论】:

    • 第一个答案已经解决了我的问题,也谢谢你..
    【解决方案2】:

    我想你想要条件聚合:

    select sum(month = 1) as january, sum(month = 2) as february
    from tablename
    where status = 'sold' and month in (1, 2)
    

    这只会生成一行,两列分别称为januaryfebruary,每列包含该月的行数。

    或者您可能想要每月一排。在这种情况下,您可以使用简单的聚合:

    select month, count(*) cnt
    from tablename
    where status = 'sold' and month in (1, 2)
    group by month
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2015-05-02
      • 2011-07-24
      • 1970-01-01
      相关资源
      最近更新 更多