[英]Compare rows with same identifier in same table
我在數據庫(SQL Server)中有一個看起來像這樣的表
+---------------------------------------------+
| id | p_id | dummyColumn2 | l_id |
+---------------------------------------------+
| 1 | 8 | someData1 | 20 |
+----+--------------+--------------+----------+
| 2 | 13 | someData2 | 20 |
+----+--------------+--------------+----------+
| 3 | 8 | someData1 | 21 |
+----+--------------+--------------+----------+
| 4 | 13 | someData2_c | 21 |
+---------------------------------------------+
我想比較具有相同 p_id 但具有不同 l_id 的行是否相同,如果不同,則獲取 p_id。 (在這種情況下,查詢應該返回 13,因為它與 p_id = 13 的第二條記錄不同)
一些附加信息:想象 p_id 代表唯一標識符,l_id 代表最新插入的記錄,所以我將舊行(l_id = 20)與新行(l_id = 21)進行比較,並獲取它是否已更改。
另請注意,此表已簡化,因此在實際情況下,它有更多的列和行
非常感謝任何幫助,並想知道是否可以使用 Joins 解決此問題。
- 我想出了一個查詢,但它似乎不起作用
//Getting latest l_id
declare @a int
set @a = (Select top(1) l_id from thisTable order by l_id desc)
SELECT NEW.p_id
FROM thisTable AS OLD
INNER JOIN thisTable AS NEW
ON OLD.p_id = NEW.p_id
WHERE OLD.l_id = @a-1
AND NEW.l_id = @a
AND OLD.dummyColumn2 <> NEW.dummyColumn2
AND ... (same for other columns)
使用聚合我們可以嘗試:
SELECT p_id
FROM thisTable
GROUP BY p_id
HAVING COUNT(*) > 1 AND MIN(l_id) <> MAX(l_id);
我認為應該返回 8 和 13 的p_id
值,因為它們的兩個l_id
值不同。
不知道我是否有問題:)
Select * from
thistable as A
join thistable as B on A.P_ID=B.P_ID
where A.l_id<>B.l_ID and A.dummycolumn2<>B.dummycolumn2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.