开发者

my sql field sum using another field to differentiate and then sort it

I would like to ask something about query using mysql

I have this table called video_stat, and here's the field

CREATE TABLE IF NOT EXISTS `video_stat` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `video_id` int(10) NOT NULL,
  `member_id` int(10) NOT NULL,
  `counter` int(11) NOT NULL,
  `daydate` varchar(15) NOT NULL,
  `monthdate` varchar(10) NOT NULL,
  `epochtime` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1

the 'counter' field will be updated per day

and my question is that, I would like to sort this field, by sum-ing the counter as total per video_id and then sort them by total per video_id to then display the list on a popular video page. how can I do that?

I thought that it would work using this query:

SELECT SUM( counter ) AS total_viewed, member_id, video_id
FROM member_video_stat

but it will only sums up everything on the counter field and return a single row since the SUM(counter) part did not count for each and particular video_id

illustration:

current table

+--------------+-----------+---------+
| id| video_id | mem开发者_StackOverflow社区ber_id | counter | 
+---+----------+-----------+---------+
| 4 |      6   |       2   |       1 |
| 5 |      9   |       6   |       1 |
| 6 |      12  |       2   |       1 |
| 7 |      6   |       2   |       1 |
| 8 |      12  |       2   |       1 |
+--------------+-----------+---------+

to something like

    +----------+-----------+---------+
    | video_id | member_id | total   |
    +----------+-----------+---------+
    |      6   |       2   |       2 |
    |      9   |       6   |       1 |
    |      12  |       2   |       2 |
    +----------+-----------+---------+


Give this a try

SELECT SUM(counter) AS total_viewed, member_id, video_id
FROM member_video_stat
GROUP BY video_id
ORDER BY total_viewed DESC

Hoa

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜