SQL:对行进行计数和分组

时间:2013-10-03 16:04:57

标签: mysql sql count

id | userid | exerciseid | date                | time | weight | distance | reps
1  | 24     | 1          | 2013-09-28 00:00:00 | 2321 | 231    | 121      | NULL
2  | 24     | 24         | 2013-09-28 00:00:00 | 2321 | 231    | 121      | NULL
3  | 24     | 1          | 2013-09-28 00:00:00 | 2321 | 231    | 121      | NULL
4  | 24     | 1          | 2000-00-00 00:00:00 | NULL | 100    | NULL     | 2
5  | 24     | 1          | 2013-09-28 00:00:00 | 2321 | 231    | 121      | NULL

第1,3和5行是相同的。我想做一个将它们组合在一起的计数,同时还添加一个带有计数值的列。

SELECT id, userid, exerciseid, date, time, weight, distance, reps    
FROM `exercises`
WHERE `userid` = 1 AND `date` < now()

所以我希望这也能返回类似的东西:

id | userid | exerciseid | date                | time | weight | distance | reps | count
1  | 24     | 1          | 2013-09-28 00:00:00 | 2321 | 231    | 121      | NULL | 3
4  | 24     | 1          | 2000-00-00 00:00:00 | NULL | 100    | NULL     | 2    | NULL

2 个答案:

答案 0 :(得分:1)

试试这个

SELECT id, userid, exerciseid, date, time, weight, distance, reps,
       count(*) as count
FROM `exercises`
WHERE userid = 1 AND date < now()
GROUP BY id, userid, exerciseid, date, time, weight, distance, reps    

答案 1 :(得分:0)

试试这个:

SELECT Count(*) As CountM, id, userid, exerciseid, date, time, weight, distance, reps    
FROM `exercises`
WHERE `userid` = 1 AND `date` < now()
Group by id, userid, exerciseid, date, time, weight, distance, reps