简体   繁体   中英

SQL: getting COUNT for each N

Is there a way to count the times every unique like_user_id is in the rows?
Adding onto this; is there a way to output this to a table with like_user_id and count ?

I've already tried the following, but this only does it for like_user_id = 2 .

Here's the table I have. link

SELECT *, COUNT(`like_user_id`) FROM `xf_liked_content`
WHERE `xf_liked_content`.`like_user_id` = 2;

this is actually very simple.

All you need to do is to group them by the term like_user_id and select it, and its count! Here is a full example:

SELECT like_user_id, count(like_user_id) FROM xf_liked_content GROUP BY like_user_id

There are a lot of constraints on how to use GROUP BY , for instance AFAIK, you cannot SELECT a term that is not on your GROUP BY list, but this is no issue in your case. For more information on the group by statement, please check https://www.w3schools.com/sql/sql_groupby.asp .

Enjoy programming!

Try to use this code:

select 'like_user_id', count(*) as cnt
from 'xf_liked_content'
group by 'like_user_id'

Or this, diffenetly depends on your DBMS:

select "like_user_id", count(*) as cnt
from "xf_liked_content"
group by "like_user_id"

Or next code:

select like_user_id, count(*) as cnt
from xf_liked_content
group by like_user_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM