Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Get common values by grouping rows

Tags:

sql

mysql

Suppose I have a table like this:

| uid | group_id | 
-----------------
|   1 |     1    |
|   1 |     2    |
|   1 |     3    |
|   1 |     4    |
|   2 |     1    |
|   2 |     2    |
|   2 |     3    |
|   3 |     1    |
|   3 |     2    |
|   3 |     4    |
...

How can I get the common set of group_ids for some set of uids.

For e.g.
for uid 1,2 : The common group_ids are 1,2,3
for uid 1,2,3 : The common group_ids are 1 and 2

like image 646
Rahul garg Avatar asked Dec 22 '12 14:12

Rahul garg


People also ask

How do I group the same values in SQL?

The SQL GROUP BY Statement The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do you SELECT the first value in a GROUP BY a bunch of rows?

First, you need to write a CTE in which you assign a number to each row within each group. To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ).

Can we use SELECT * with GROUP BY?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.


1 Answers

Assuming each group_ID is unique for every uid, (otherwise you need to use distinct)

SELECT group_ID
FROM tableName
WHERE uid IN (1,2,3)
GROUP BY group_ID
HAVING COUNT(*) = 3
  • SQLFiddle Demo (includes two queries)
like image 110
John Woo Avatar answered Oct 11 '22 01:10

John Woo