0

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

考虑 r 下表数据:

+---------+------------+-------------+--------------+
| 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)是相同的。我想同时获得这两个值。C001C002

最终输出应如下所示:

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

4 回答 4

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

做这个把戏?

于 2014-03-20T11:02:40.053 回答
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`);
于 2014-03-21T08:40:00.163 回答
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
于 2014-03-21T09:00:57.450 回答
-1

如果我理解正确,以下代码可以解决您的问题:

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

SQLFIDDLE 示例:

于 2014-03-20T11:34:06.633 回答