简体   繁体   中英

How to get a field with a certain amount of sub-field in SQL?

I don't think i phrased the question correctly. I am trying to grab all the GroupID fields from a table that have more then 6 UserID fields:

Here's what my table "group_members" looks like

|  GroupID  |  UserID  |  role  |
_________________________________

|  22       |  02      |  role  |
|  22       |  03      |  role  |
|  25       |  01      |  role  |
select * from group_members
group by GroupID
having count(*) >6

Selecting all GroupID that have more than 6 UserID , or in other words GroupID that appear in 6 rows (and the UserID s are not NULL ):

SELECT GroupID
FROM group_members
GROUP BY GroupID
HAVING COUNT(UserID) > 6

Selecting all GroupID that have more than 6 DISTINCT UserID s:

SELECT GroupID
FROM group_members
GROUP BY GroupID
HAVING COUNT(DISTINCT UserID) > 6

you need to use a GROUP BY and HAVING statement in your SQL. Also note, that the UserID column must be a number data-type (there are many variants, but in your case in your case probably an integer)

the SQL:

select GroupID 
FROM group_members
GROUP BY GroupID
HAVING count(*) >6

more info on group by statement: http://www.w3schools.com/sql/sql_groupby.asp more info on having statement: http://www.w3schools.com/sql/sql_having.asp

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