2013-03-19 69 views
1

這行是我的示例表:SQL查詢 - 選擇具有至少兩個重複的值

|"id","singlesaleid","quantity" 
------------------------------------- 
| 1, "00278e0f", 37 
| 2, "00278e0f", 38 
| 3, "002ebd2e", 37 
| 4, "00380783", 37 
| 5, "003b3c35", 37 
| 6, "003b3c35", 38 
| 7, "0042170b", 38 
| 8, "00421b89", 37 
| 9, "00421b89", 38 
| 10, "00587f02", 37 
| 11, "00799433", 38 
| 12, "00799433", 37 

如何使選擇的選擇和組僅此行,在singlesaleid列至少有兩個重複的值?

的結果應該是:

|"id","singlesaleid","quantity" 
------------------------------------- 
| 1, "00278e0f",  37 
| 6, "003b3c35",  38 
| 9, "00421b89",  38 
| 12, "00799433",  37 

有人能幫忙嗎?

回答

2
SELECT a.* 
FROM TableName a 
     INNER JOIN 
     (
      SELECT singlesaleid, MIN(quantity) min_val 
      FROM TableName 
      GROUP BY singlesaleid 
      HAVING COUNT(*) > 1 
     ) b a.singlesaleid = b.singlesaleid AND 
      a.quantity = b.Min_Val 
+0

錯誤的'id' /'quantity' – MarcinJuraszek 2013-03-19 09:18:29

+0

@MarcinJuraszek這是因爲OP確實已經知道如何選擇這個值。順便說一下,它會從上面的一行中獲得正確的值。 – 2013-03-19 09:19:27

+0

@MarcinJuraszek看到這個記錄,OP如何選擇記錄1和2以及11和12?通過最低數量的權利?這與記錄「5和6」和「8和9」不同,因爲他選擇最高數量。 – 2013-03-19 09:21:33

0

如果你想要的任何一種具有至少2次重複的只有那些singlesaleid's記錄(只有一個),那麼試試下面代碼..

select * from table where rowid in 
(select min(rowid) from table 
group by singlesaleid 
having count(*)>=2) 
+0

我有一個錯誤:'字段列表'中的未知列'rowid' – unky 2013-03-19 17:29:22

+0

您正在使用哪個rdbms?上面的查詢將在'Oracle'中運行 – Aspirant 2013-03-20 05:07:32

0

而且您可以使用EXISTS()運營商的選項。雖然,我不太明白,什麼行應從組中選擇,在選定的請求與MAX(t2.Id)行

SELECT * 
FROM Tablename t1 
WHERE EXISTS (
       SELECT * 
       FROM Tablename t2 
       WHERE t1.singlesaleid = t2.singlesaleid 
       HAVING COUNT(*) > 1 AND MAX(t2.Id) = t1.id 
      ) 

演示上SQLFiddle