简体   繁体   中英

SQL query count = 0/null

I have the following MySql table with ~19000 entries like this:

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...................................................................

I would like to get a list like this:

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

I have a query for every column like this:

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)

The problem is that "group by" does not list the count(...) entries as

USER     valid
...
name3    0

So the 4 query results do not have the same rowcount. How can I solve this Problem?

You are trying to do this:

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. User Name
  2. Number of entries of the user
  3. Number of entries of entries with some int different of NULL
  4. Number of entries where Error is missing`
  5. Number of entries where ERROR is syntax

PD: Maybe you want to add the LIMIT 0,20000 at the end of the query. I didn't do that because I didn't get the purpose.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM