【问题标题】:mysql count column value for distinct values in other columnsmysql计算其他列中不同值的列值
【发布时间】:2017-06-26 09:21:05
【问题描述】:

我有一张表,我需要在其中返回两件事(最好使用一个查询):
1) 每个日期的唯一 ID 计数
2) otherfield = "-" 为唯一 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。

提前谢谢你。

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

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

    【讨论】:

    • 谢谢,这是最快的查询
    • 是的,这比我的解决方案好得多
    【解决方案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
    

    【讨论】:

    • 我希望它会更简单一些,它看起来很复杂,但它确实有效。谢谢
    【解决方案3】:

    使用子查询怎么样?

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

    【讨论】:

    • 更新了我的答案。但是,我不在办公室,没有什么可测试的。但是子查询应该是一个尝试的方向。
    猜你喜欢
    • 2019-03-09
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多