sql查询:显示具有group By子句的所有行

时间:2013-11-07 10:11:41

标签: mysql sql

使用group By子句时是否可以显示所有表行? exp:

id      user_id   gift_id  
 1        1          1     
 2        1          2     
 3        1          1    
 4        2          3    
 5        2          1    
 6        3          4    

预期结果:(按user_id计算后)

id      user_id   gift_id   count 
 1        1          1       3
 2        1          2       3
 3        1          1       3
 4        2          3       2
 5        2          1       2
 6        3          4       1

2 个答案:

答案 0 :(得分:2)

试试这个

select a.*, b.user_count from tablename as a join 
(select user_id, count(*) as user_count from tablename group by user_id) as b on
a.user_id= b.user_id 

答案 1 :(得分:0)

SELECT id
     , user_id
     , gift_id
     , Count(user_id) over (PARTITION BY user_id) nb_user_id
FROM matable