我有一张像这样的表
c_id b_id
13 151
27 203
38 347
38 349
38 357
72 132
72 475
104 14
151 22
207 690
207 712
如您所见,该表首先由c_id排序,然后由b_id排序。 我想删除每个c_id的第一个条目。
所以我的输出表应该是这个
c_id b_id
38 349
38 357
72 475
207 712
只删除了与其关联的b_id的c_id。并且已删除其他c_ids的第一个b_ids。
可以使用多个查询。原始表中有数百万行。
答案 0 :(得分:2)
SELECT cb.c_id, cb.b_id
FROM cb
LEFT JOIN (
SELECT c_id, MIN(b_id) AS minb_id
FROM cb
GROUP BY c_id
) cbmin ON cb.c_id = cbmin.c_id AND cb.b_id = cbmin.minb_id
WHERE cbmin.c_id IS NULL
答案 1 :(得分:1)
SELECT *
FROM
(
SELECT c_id, b_id,
ROW_NUMBER() OVER(PARTITION BY c_id ORDER BY c_id DESC) RowNum
FROM TestTable
WHERE c_id IN
(
SELECT c_id
FROM TestTable
GROUP BY c_id
HAVING COUNT(b_id) > 1
)
) t WHERE RowNum > 1
这应该给你以下内容:
c_id b_id RowNum
--------------------
38 349 2
38 357 3
72 475 2
207 712 2
答案 2 :(得分:1)
首先选择c_id
列表SELECT c_id FROM TABLE GROUP BY c_id
获取每个c_id的第一个元素并删除
DELETE FROM TABLE
WHERE ID = (SELECT ID
FROM (SELECT ROW_NUMBER () OVER (ORDER BY ID) row_no, a.*
FROM TABLE a
WHERE a.ID = 11)
WHERE row_no = 1)
答案 3 :(得分:1)
SELECT cb.c_id, cb.b_id
FROM cb
LEFT JOIN cb cbmin ON cb.c_id = cbmin.c_id
GROUP BY cb.c_id, cb.b_id
HAVING cb.b_id > MIN(cbmin.b_id)