MySQL-根据同一列的不同值计算总记录数

时间:2021-05-05 07:22:57

标签: mysql

我有一个表格如下

table_user

id                name                   status                     flag                   country
====================================================================================================
1                  AB                       1                          0                     US
2                  BC                       1                          0                     UK
3                  CD                       0                          0                     IN
4                  DE                       3                          0                     BR
5                  EF                       3                          0                     UK
6                  FG                       2                          0                     IN
7                  GH                       4                          0                     IN

我想数数。记录在哪里

status = 1 as totalactiverecords,

status = 0 作为 totalinactiverecords,

status = 3 作为 totalrecentactiverecords,

status = 2 作为 totalemailnotverifiedrecords,

status = 4 as totalemailverifiedrecords,

,而 countryUK都在一个 单个 SELECT 语句.

有什么具体的方法吗?

我想到了类似的东西

SELECT COUNT(*) as totalactiverecords  WHERE status=1 
        COUNT(*) as totalinactiverecordsWHERE status=0,
        COUNT(*) as totalemailnotverifiedrecords WHERE status=2,
        COUNT(*) as totalrecentactiverecords WHERE status=3,
        COUNT(*) as totalemailverifiedrecords WHERE status=4

FROM table_user where country=IN

,但这似乎不起作用。

2 个答案:

答案 0 :(得分:1)

你可以试试这个查询:

SELECT count(case status when '1' then 1 else null end) as totalactiverecords,
    count(case status when '0' then 1 else null end) as totalinactiverecords,
    count(case status when '2' then 1 else null end) as totalemailnotverifiedrecords,
    count(case status when '3' then 1 else null end) as totalrecentactiverecords,
    count(case status when '4' then 1 else null end) as totalemailverifiedrecords 
FROM table_user where country='IN'

答案 1 :(得分:1)

我通常在此类问题中使用 % alias hello="echo hello" % myfunc2 () { eval "${(q)@}" } % myfunc2 hello '()' hello () % myfunc2 hello \(\) \(')' '('\) hello () () () %

CASE WHEN