[英]SQL Server query - get items that exist in more than one column
我有一個簡單的表格,其中包含工具的條形碼ID和該工具應所屬的相關房間位置。
不幸的是,我注意到有些用戶為另一個房間位置輸入了相同的條形碼ID。
例如,我有以下兩列:
barcodeNumber | RoomLocation
--------------+-------------
123456 | 400
654321 | 300
875421 | 200
654321 | 400
999999 | 250
878787 | 300
777777 | 400
999999 | 200
請注意,條形碼編號“ 654321”存儲在房間位置300和400,廣告“ 999999”存儲在房間位置200和250
如何編寫SQL查詢以列出重復的條形碼編號和RoomLocation,而不只是重復的“計數”?
例如,我希望看到的最終結果是:
654321 | 300
654321 | 400
999999 | 200
999999 | 250
使用窗口函數(SQL:1999),您將得到如下結果:
with c as (
select barcodeNumber, RoomLocation,
count(*) over(partition by barcodeNumber) cnt
from t)
select barcodeNumber, RoomLocation
from c where cnt > 1
order by 1,2
您還可以使用SQL-92語法:
select barcodeNumber, RoomLocation
from t
where barcodeNumber IN (
select barcodeNumber from t
group by barcodeNumber
having count(*) > 1)
order by 1,2
您也可以嘗試一下。 使用count(*) over (partition by barcodenumber)
來確定重復值。
create table #sample (barcodenumber nvarchar(30),roomlocation int)
insert into #sample (barcodenumber,roomlocation)
select '123456',400 union all
select '654321',300 union all
select '875421',200 union all
select '654321',400 union all
select '999999',250 union all
select '878787',300 union all
select '777777',400 union all
select '999999',200
select barcodenumber,roomlocation from (
select *, count(*) over (partition by barcodenumber) as rnk
from #sample
)t
group by barcodenumber,roomlocation,rnk
having rnk >1
希望這會有所幫助。
您是否要查找重復的條形碼?
;WITH tb(barcodenumber,roomlocation)AS(
SELECT '123456',400 UNION ALL
SELECT '654321',300 UNION ALL
SELECT '875421',200 UNION ALL
SELECT '654321',400 UNION ALL
SELECT '999999',250 UNION ALL
SELECT '878787',300 UNION ALL
SELECT '777777',400 UNION ALL
SELECT '999999',200
)
SELECT * FROM (
SELECT *,COUNT(0)OVER(PARTITION BY tb.barcodenumber) AS cnt FROM tb
) AS t WHERE t.cnt>1
barcodenumber roomlocation cnt ------------- ------------ ----------- 654321 400 2 654321 300 2 999999 200 2 999999 250 2
這是獲得結果的另一種方法:
SELECT barcodenumber, roomlocation
FROM table_name
WHERE barcodenumber IN (
SELECT barcodenumber
FROM table_name
GROUP BY barcodenumber
HAVING COUNT(DISTINCT roomlocation) > 1);
--If you dont have duplicate rows then just use COUNT(*)
使用JOIN和HAVING子句:
SELECT A.barcodenumber,roomlocation
FROM #sample
JOIN
(
SELECT barcodenumber
FROM #sample
GROUP BY barcodenumber
HAVING COUNT(*) > 1
) A ON A.barcodenumber = #sample.barcodenumber
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.