Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql count column value for distinct values in other columns

Tags:

sql

mysql

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.

like image 576
MirrorMirror Avatar asked Nov 01 '25 11:11

MirrorMirror


2 Answers

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;
like image 134
Gordon Linoff Avatar answered Nov 04 '25 00:11

Gordon Linoff


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
like image 44
Oto Shavadze Avatar answered Nov 04 '25 00:11

Oto Shavadze



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!