SQL如何group_by和计数

时间:2019-02-14 19:42:22

标签: sql

我有以下查询

 SELECT c.`name` as categories,times_booked.booked as booked
              FROM req_profiles rq                
                                inner join categories as c on c.id = rq.category_id
              left join 
                (
                SELECT rq.id, COUNT(rq.id) as booked
                FROM req_profiles as rq
                inner join profile_matchings as pm on pm.req_profile_id = rq.id
                WHERE pm.`status` =  'booked'
                AND rq.user_id = 736
                AND (pm.created_at BETWEEN '2018-01-01 00:00' AND '2019-02-13 00:00')
                GROUP BY rq.id
                ) as times_booked on times_booked.id = rq.id

              where rq.user_id=736
                                and rq.`status` = 'active'

              ORDER BY times_booked.booked,rq.id desc           
                                limit 5

这就是我得到的:

categories| booked
-------------------
  Talent      NULL
  Talent       1
  Talent       1

但是我想得到这样的结果:

categories| booked
-------------------
  Talent      2

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

将您的查询用作

的子查询anf组
select categories, count(booked)
from (
     SELECT c.`name` as categories,times_booked.booked as booked
                  FROM req_profiles rq                
                                    inner join categories as c on c.id = rq.category_id
                  left join 
                    (
                    SELECT rq.id, COUNT(rq.id) as booked
                    FROM req_profiles as rq
                    inner join profile_matchings as pm on pm.req_profile_id = rq.id
                    WHERE pm.`status` =  'booked'
                    AND rq.user_id = 736
                    AND (pm.created_at BETWEEN '2018-01-01 00:00' AND '2019-02-13 00:00')
                    GROUP BY rq.id
                    ) as times_booked on times_booked.id = rq.id

                  where rq.user_id=736
                                    and rq.`status` = 'active'

                  ORDER BY times_booked.booked,rq.id desc           
                                    limit 5
    ) t 
    group by categories 

答案 1 :(得分:0)

select x.a, count(x.b) 
from (
select 'a' a, 10 b from dual
union all
select 'a' a, 20 from dual
union all 
select 'b' a, 10 from dual 
)x

希望有帮助!