简体   繁体   中英

SQL return COUNT() of rows separated by criteria

I need to COUNT() (or maybe another MySQL function) rows of my query, but I need diferent counts, like this:

What I am getting:

   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

What I need:

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

You need a simple group by query. I suspect you are leaving the id in the group by. Try something like this:

select max(id), date, customer_id, count(*)
from t
group by date, customer_id
order by 1
SELECT id, `date`, customer_id, COUNT(1) AS `count`
FROM `table`
GROUP BY `customer_id`

You have to use GROUP BY

Below query will give you desired results :

select id, date, costumer_id ,count(costumer_id) as c from table1 group by costumer_id order by c desc

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM