获取mysql中重复值的多个最大计数

时间:2014-03-20 10:30:33

标签: mysql sql groupwise-maximum

如何从表中获取最大重复值计数的输出,该表包含与列对应的重复值,以便存在多个具有最大计数的不同不同值。

考虑以下表格数据:

+---------+------------+-------------+--------------+
| Bill_No | Bill_Date  | Customer_ID | Total_Amount | 
+---------+------------+-------------+--------------+
|     101 | 2012-04-10 | C001        |           64 |
|     102 | 2012-04-10 | C002        |            8 |
|     103 | 2012-04-11 | C002        |          140 |
|     104 | 2012-04-13 | C001        |           29 |
|     105 | 2012-04-12 | C003        |          125 |
|     106 | 2012-04-16 | C004        |          258 |
+---------+------------+-------------+--------------+    

我们在此处看到count(customer_id)C001的最大C002相同。我想得到两个值。

最终输出应如下所示:

customer_id     |    count(customer_id)  //max value
----------------+-----------------------
C001            |    2                  
C002            |    2                  
----------------+-----------------------

4 个答案:

答案 0 :(得分:1)

所以,有些猜测,会

select
    distinct g.customer_id,
    g.cnt
from
    (
    select
        distinct customer_id,
        count(customer_id) cnt
    from
        table
    group by 
        customer_id
    ) g
inner join
    (
    select
        max(s.cnt) max_cnt
    from
        (
        select
            distinct customer_id,
            count(customer_id) cnt
        from
            table
        group by
            customer_id
        ) s
    ) m
on
    m.max_cnt = g.cnt

诀窍?

答案 1 :(得分:0)

如果我理解正确,下面的代码解决了你的问题:

SELECT cid, COUNT(cid)  FROM t GROUP BY cid;

SQLFIDDLE EXAMPLE:

答案 2 :(得分:0)

只需使用多个步骤。

首先保存每个customer_id的计数。然后选择具有MAX计数的customer_ids。

CREATE TEMPORARY TABLE `tmp_count` SELECT count(*) as noOf, customer_id FROM `table` GROUP BY customer_id;
SELECT noOf, customer_id FROM `tmp_count` WHERE noOf = (SELECT MAX(noOf) FROM `tmp_count`);

答案 3 :(得分:0)

试试这个,

;With CTE as
(
SELECT Customer_ID, COUNT(Customer_ID) as Counts
, Rank() over (order by COUNT(Customer_ID) desc) as Rnk
  FROM t GROUP BY Customer_ID 
)
select * from Cte
Where Rnk = 1