简体   繁体   中英

SQL query that match all list with group by

I have table that,

-----------dates-------------
| id | date       | user_id |
| 1  | 2016-01-01 |    1    |
| 2  | 2016-01-02 |    1    |
| 3  | 2016-01-03 |    1    |
| 4  | 2016-01-04 |    1    |
| 5  | 2016-01-01 |    2    |
| 6  | 2016-01-02 |    2    |
| 7  | 2016-01-03 |    2    |
| 8  | 2016-01-01 |    3    |
| 9  | 2016-01-02 |    3    |

I want to make query that to get user_id match all date

like,

SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04')
#=> result: 1

SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03')
#=> result: 1, 2

SELECT user_id FROM dates WHERE xxxxxx IN ('2015-01-01', '2015-01-02')
#=> result: 1, 2, 3

Actually, my solution is using group by with count, but date can be duplicated. Any other solution?

I use postgresql

You can use group by and having :

SELECT user_id
FROM dates
WHERE xxxxxx IN ('2015-01-01', '2015-01-02', '2015-01-03', '2015-01-04')
HAVING COUNT(DISTINCT xxxxxx) = 4;

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