How to count and group query to get proper results?

喜夏-厌秋 提交于 2020-01-24 11:44:05

问题


I have a problem, please see my database:

-------------------
| id | article_id |
-------------------
| 1  |      1     |
| 2  |      1     |
| 3  |      1     |
| 4  |      2     |
| 5  |      2     |
| 6  |      3     |
| 7  |      3     |
| 8  |      3     |
| 9  |      3     |
| 10 |      3     |

And I want to receive something like this (order by votes, from max to min):

---------------------------
| id | article_id | votes |
---------------------------
| 1  |      3     |    5  |
| 2  |      1     |    3  |
| 3  |      2     |    2  |

Could you please help me to write proper sql query?


回答1:


SELECT article_id, COUNT(article_id) AS votes
FROM votes_table
GROUP BY article_id
ORDER BY votes DESC;



回答2:


SET @currentRow = 0;
SELECT @currentRow := @currentRow + 1 AS id, t.article_id, t.c AS `votes`
FROM (
    SELECT article_id, count(*) as `c`
    FROM table_votes
    GROUP BY article_id
    ) t
ORDER BY t.c DESC

please note that you can't select an id column like this in this context, and your "expected result" is incorrect. I tried to adapt it at a maximum.

cheers



来源:https://stackoverflow.com/questions/10776519/how-to-count-and-group-query-to-get-proper-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!