对于其他列中不同的值,统计MySQL列值的数量

4

我有一张表需要返回两个东西(最好只用一个查询):
1)每天唯一ID的计数
2)其他字段为“-”的唯一ID的行数。这意味着,如果同一天的ID在otherfield中输入了两次值“-”,我希望将其视为一次计数。

示例表:

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

应该返回表格:
date1 | 2 | 1
date2 | 2 | 0

目前我正在使用:

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

但是这个代码对otherfield中的所有值求和,对于id='p'的条目计数两次,我希望它只对不同的id计数。
提前感谢您。
3个回答

9
只需使用条件 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;

1
谢谢,这是最快的查询。 - MirrorMirror
是的,这比我的解决方案好多了。 - Oto Shavadze
只是想指出这是一个惊人的解决方案! - Chris Kelker

2

一种可能的方法:

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

我本以为它会更简单,但看起来很复杂,不过它能正常工作。谢谢。 - MirrorMirror

0

使用子查询怎么样?

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

更新了我的回答。然而,我不在办公室,并且没有任何可供测试的东西。但子查询应该是一个尝试的方向。 - Chris Lam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接