Pregunta

How can I get the output for maximum count of repeated values from a table, which contains the repeated values corresponding to a column such a way that there are multiple different distinct values having maximum-counts.

Consider r the table data below :

+---------+------------+-------------+--------------+
| 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 |
+---------+------------+-------------+--------------+    

We see here maximum count(customer_id) is same for C001 and C002. I want to get both values.

The final output should look like follows:

customer_id     |    count(customer_id)  //max value
----------------+-----------------------
C001            |    2                  
C002            |    2                  
----------------+-----------------------
¿Fue útil?

Solución

So, with some guessing, would

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

do the trick?

Otros consejos

Just use multiple steps.

First save the count for every customer_id. Then select the customer_ids which have the MAX count.

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`);

Try this,

;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

if i understand correctly following code is solve you problem:

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

SQLFIDDLE EXAMPLE:

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top