mysql行值为count(*)的列

xxb16uws  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(353)

我有一个结构如下的表,我试图用行值作为列,用它们的值作为出现的次数。

|  date     |order|status|
-----+-----+----------------
| 2018-05-22|    1|  closed|
| 2018-05-22|    2|  closed|
| 2018-05-22|    3|  closed|
| 2018-05-22|    4|  open  | 
| 2018-05-22|    4|  open  |

输出:

|  date     |closed|open|
-----+-----+----------------
| 2018-05-22|   3  |  2|

当我使用下面的查询来获取count(*)值时,我得到一个错误“组函数的使用无效”

select date,
  max(case when `status` ='closed' then count(*) end) closed,
  max(case when `status` = 'open' then count(*) end) open
from orders where date ='2018-05-22' group by date,status

感谢你的帮助。。。

6tdlim6h

6tdlim6h1#

下面呢?

select
  date,
  sum(case when `status` ='closed' then 1 else 0 end) closed,
  sum(case when `status` = 'open' then 1 else 0 end) open
from orders where date ='2018-05-22' group by date

相关问题