SQL查询计数= 0 / null

时间:2014-08-08 08:54:46

标签: mysql sql count

我有以下MySql表,其中包含~19000个条目:

ID      USER        FIELD1         FIELD2         SOMEINT   ERROR
1       name1       null           null           null      missing...
2       name1       value1         value2         3         validated!
3       name1       value3         wrongvalue1    null      syntax
4       name2       wrongvalue2    value4         null      syntax
etc...................................................................

我想得到一个这样的列表:

USER    totalEntries     totalValid   totalMissing    totalSyntax
name1   3                1            1               1
name2   1                0            0               1
etc...................................................................

我对每个列都有一个查询:

select user, count(user) valid from table where 
someint is not null group by user limit 0, 20000;
(total valid entries)

select user, count(*) totalEntries from table group by user
limit 0, 20000; (total entries)

select user, count(*) totalMissing from table where field1 is null or
field2 is null group by user limit 0, 20000; (total Missing entrie)

select user, count(*) syntax from table where error like 'syntax%'
group by user limit 0, 20000 (syntaxerror entries)

问题是"分组"不会将count(...)条目列为

USER     valid
...
name3    0

因此4个查询结果没有相同的rowcount。我怎么解决这个问题?

1 个答案:

答案 0 :(得分:3)

您正在尝试这样做:

SELECT user, COUNT(*) as totalEntries, 
    SUM(CASE WHEN someint IS NOT NULL THEN 1 ELSE 0 END),
    SUM(CASE WHEN field1 IS NULL OR field2 IS NULL THEN 1 ELSE 0 END),
    SUM(CASE WHEN error LIKE 'syntax%' THEN 1 ELSE 0 END)
FROM SomeTable
GROUP by user
  1. 用户名
  2. 用户的条目数
  3. 条目的条目数,其中某些int与NULL
  4. 不同
  5. Error is缺少的条目数
  6. ERRORsyntax
  7. 的条目数

    PD:也许你想在查询结尾添加LIMIT 0,20000。我没有这样做,因为我没有达到目的。