我有一张桌子,我需要返回两件事(最好有一个查询):
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。
提前谢谢。
答案 0 :(得分:3)
只需使用条件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 :(得分: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
答案 2 :(得分: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