简体   繁体   中英

mysql count column value for distinct values in other columns

I have a table where I need to return two things (preferably with one query):
1) the count of unique ids per date
2) the number of rows where otherfield = "-" for unique ID. This means, if an id in the same day enters twice the value "-" in otherfield , I want it to count it as one.

example table:

date | id | otherfield
----------
date1 | f  | abc
date1 | p  | -
date1 | p  | -
date2 | f  | abc
date2 | d  | dee

should return table:

date1 | 2 | 1
date2 | 2 | 0

currently I'm using:

SELECT date, COUNT(DISTINCT `id`) AS id, SUM(IF(otherfield = '-', 1,0)) AS `undeclared` FROM mytable GROUP BY date

but this sums up all values of otherfield, counting the entries for id='p' twice, I want it only to count for distinct id.

Thank you in advance.

Just use a conditional count distinct :

select date, count(distinct `id`) as num_ids, 
       count(distinct case when otherfield = '-' then id end) as undeclared
from mytable 
group by date;

One possible way:

select t1.date, t1.id_cnt, t2.dash_cnt from (
    select date, count( distinct id ) as id_cnt from your_table
    group by date
) t1
left join(
    select date, sum(dash_cnt) as dash_cnt from (
        select date, id, 1 as dash_cnt from your_table
        where otherfield = '-'
        group by date, id 
    ) t
    group by date
) t2 
on t1.date = t2.date

How about using subquery?

SELECT 
    date, COUNT(DISTINCT id),
    (SELECT COUNT(*) FROM mytable WHERE otherfield = '-' WHERE id = t.id GROUP BY id)
FROM mytable t
GROUP BY date

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