我的表格如下:
ID - USER - LOCATION
1 - Steve - home
2 - Steve - work
3 - Steve - school
4 - Eve - home
5 - Eve - work
6 - Eve - school
7 - RJ - school
etc.
如何从所有用户那里获得两个职位?
修改
输出应为:
ID - USER - LOCATION
1 - Steve - home
2 - Steve - work
4 - Eve - home
5 - Eve - work
7 - RJ - school
答案 0 :(得分:2)
SELECT x.*
FROM my_table x
JOIN my_table y
ON y.user = x.user
AND y.id <= x.id
GROUP
BY x.id
HAVING COUNT(*) <=2;
+----+-------+----------+
| ID | USER | LOCATION |
+----+-------+----------+
| 1 | Steve | home |
| 2 | Steve | work |
| 4 | Eve | home |
| 5 | Eve | work |
| 7 | RJ | school |
+----+-------+----------+
E.g:
submit
答案 1 :(得分:0)
类似的东西:
public static void Main(string[] args) { ... }
或者,如果您想要2个特定位置:
SELECT a.USER
FROM YourTable a
WHERE LOCATION IN (
SELECT DISTINCT(b.LOCATION)
FROM YourTable b
WHERE USER = a.USER
LIMIT 2
)
编辑:
似乎MySql(或某些版本)不接受SELECT USER
FROM YourTable
WHERE LOCATION = 'home' OR LOCATION = 'work'
进入子查询