嗨我有这样一张桌子:
notifies
id,user_id
1,3
2,3
3,4
4,5
5,6
6,3
7,4
8,4
9,3
10,3
我必须创建一个只对相邻行进行分组的查询
所以,这个例子的结果应该是:
user_id
3
4
5
6
3
4
3
我该怎么做? 感谢
答案 0 :(得分:5)
SELECT user_id
FROM notifies n
WHERE NOT
(
SELECT user_id
FROM notifies ni
WHERE ni.id < n.id
ORDER BY
id DESC
LIMIT 1
) <=> user_id
答案 1 :(得分:0)
我认为最好的选择是进行非常简单的选择,将结果放到某个应用程序中,然后用更合适的(命令性)语言对其进行过滤。但是,如果你需要,我的纯MySQL版本。您必须按id
订购数据。
SELECT a.user_id
FROM notifies AS a
LEFT JOIN notifies AS c ON (
SELECT MIN(id) FROM notifies AS b WHERE b.id > a.id
) = c.id
WHERE a.user_id <> c.user_id OR c.user_id IS NULL
ORDER BY a.id
第二个例子:
SELECT c.user_id
FROM (
SELECT a.id, a.user_id, MIN(b.id) AS next
FROM notifies AS a
LEFT JOIN notifies AS b ON b.id > a.id
GROUP BY a.id, a.user_id
) AS c
LEFT JOIN notifies AS d ON d.id = c.next
WHERE c.user_id <> d.user_id OR c.next IS NULL
ORDER BY c.id
答案 2 :(得分:0)
Select N.id, N.user_id
From notifies As N
Where Exists (
Select 1
From notifies As N2
Where N2.id = N.id + 1
And N2.user_id <> N.user_id
)
答案 3 :(得分:0)
试试这个:
SQL是这样的:
SELECT [user_id] FROM (
SELECT *,
CASE WHEN (
SELECT [user_id] FROM (
SELECT ROW_NUMBER() OVER(ORDER BY id) AS [prev_id_no],
[user_id]
FROM notifies
) FILTER_IN
WHERE FILTER_IN.prev_id_no = (FILTER_OUT.id_no - 1)
) = FILTER_OUT.[user_id] THEN 'YES' ELSE 'NO' END AS [DUPLICATE]
FROM (
SELECT ROW_NUMBER() OVER(ORDER BY id) AS [id_no],
[user_id]
FROM notifies
) FILTER_OUT
) FILTER_FINAL
WHERE FILTER_FINAL.DUPLICATE = 'NO'
结果是:
user_id
3
4
5
6
3
4
3