繁体   English   中英

MySQL计数列值在其他列中的不同值

[英]mysql count column value for distinct values in other columns

我有一个表,我需要在其中返回两件事(最好是通过一个查询):
1)每个日期的唯一ID数
2)行数,其中otherfield =“-”为唯一ID。 这意味着,如果同一天的id在otherfield输入值“-”的两倍,我希望它将其计为1。

示例表:

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进行计数。

先感谢您。

只需使用一个count distinct的条件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;

一种可能的方式:

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

如何使用子查询?

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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