mysql 如何使用sql count()函数多次在同一个表与where子句[duplicate]

zbdgwd5y  于 2023-01-12  发布在  Mysql
关注(0)|答案(2)|浏览(133)
    • 此问题在此处已有答案**:

How to get multiple counts with one SQL query?(12个答案)
2天前关闭。
假设我有一张table:
| 姓名|数|日期|
| - ------|- ------|- ------|
| 名称1|小行星91104|'二〇二二年十二月一日'|
| 名称2|小行星11161|'2022年12月2日'|
我正在编写这些查询:

select count(name) from table
    where
        created_at between
            '2022-12-01' and '2022-12-10' and
        terminal_id like '911%'
select count(name) from table
    where
        created_at between
            '2022-12-01' and '2022-12-10' and
        terminal_id like '111%'

如何编写查询以获得此输出:
| 类似911|111类|
| - ------|- ------|
| 十个|二十五|

rks48beu

rks48beu1#

这是使用count(“expression”)完成的。当表达式为真时,它将计数

select count(case when terminal_id like '911%'  
                  then name
               end)  as [911like]
       ,count(case when terminal_id like '111%'  
                  then name
               end)  as [111like]
   from table
 where created_at between '2022-12-01' and '2022-12-10'
yws3nbqq

yws3nbqq2#

更简化:

select sum(terminal_id like '911%') as 911like,
       sum(terminal_id like '111%') as 111like
from my_table
where created_at between '2022-12-01' and '2022-12-10';

https://dbfiddle.uk/PqdCP0Fq

相关问题