SQL返回按条件分隔的行的COUNT()

时间:2012-10-05 17:49:33

标签: mysql count group-by

我需要COUNT()(或者可能是另一个MySQL函数)我的查询行,但我需要不同的计数,如下所示:

我得到的是什么:

   id  | date       | costumer_id
  -----+------- ----+-------------
   1   | 2012-10-05 | 103
   2   | 2012-10-05 | 103
   3   | 2012-10-05 | 103
   4   | 2012-10-05 | 59
   5   | 2012-10-05 | 59
   6   | 2012-10-05 | 90

我需要什么:

   id  | date       | costumer_id | count
  -----+------------+-------------+------
   1   | 2012-10-05 | 103         | 3
   5   | 2012-10-05 | 59          | 2
   6   | 2012-10-05 | 90          | 1

4 个答案:

答案 0 :(得分:1)

您需要一个简单的查询组。我怀疑你要离开这个小组。尝试这样的事情:

select max(id), date, customer_id, count(*)
from t
group by date, customer_id
order by 1

答案 1 :(得分:0)

SELECT id, `date`, customer_id, COUNT(1) AS `count`
FROM `table`
GROUP BY `customer_id`

答案 2 :(得分:0)

您必须使用GROUP BY

以下查询将为您提供所需的结果:

选择id,date,costumer_id,count(costumer_id)作为c from table1 group by costumer_id order by c desc

答案 3 :(得分:0)

select 
    min(id) as id, 
    date, 
    customer_id, 
    count(*) as count
from tatble
group by 
    date, 
    customer_id
order by 1;