2013-09-23 95 views
-1

處理領帶我有這樣的數據集:邏輯用於與骨料

| ID | TYPE | PERCENT | 
------|------|---------| 
| 123 | A |  0.5 | 
| 123 | B |  0.5 | 
| 456 | A |  0.7 | 
| 456 | B |  0.3 | 
| 789 | A |  1 | 

我想以下結果:

| ID | TYPE | PERCENT | 
------|------|---------| 
| 123 | A |  0.5 | 
| 456 | A |  0.7 | 
| 789 | A |  1 | 

即,獲得MAX(percent)每個id和相應type

我目前使用

SELECT ... 
FROM 
    (SELECT [id], MAX([percent]) AS [p] 
    FROM [highest] 
    GROUP BY [id]) a 
LEFT JOIN [highest] b 
    ON b.[id] = a.[id] 
    AND b.[percent] = a.[p] 

並獲得

| ID | P | TYPE | PERCENT | 
--- --|-----|------|---------| 
| 123 | 0.5 | A |  0.5 | 
| 123 | 0.5 | B |  0.5 | 
| 456 | 0.7 | A |  0.7 | 
| 789 | 1 | A |  1 | 
+0

那麼你的問題是什麼?每個ID只需要一個記錄? –

+0

@db_brad正確。 – Kermit

回答

3

嘗試此查詢:

SELECT src.[id], src.[type], src.[percent] 
FROM (
    SELECT [id], [type], [percent], 
      ROW_NUMBER() OVER(PARTITION BY h.[id] ORDER BY [percent] DESC, h.[type] ASC) AS RowNum 
    FROM [highest] h 
) src 
WHERE src.RowNum = 1 
+1

最優秀。謝謝。 – Kermit

+1

我認爲這應該是'ORDER BY h。[PERCENT] DESC',而不是'ORDER BY h。[type]',因爲您希望每個ID的最高百分比。對? http://www.sqlfiddle.com/#!3/140c0/3除非我誤解':)' –

+1

@BogdanSahlean我已經加了'DESC',忘了提及它。感謝您的更新。 – Kermit

1

另一種方法對皮膚的貓:

SELECT d.ID, m.type, m.[percent] 
FROM highest AS d 
CROSS APPLY (
    SELECT TOP 1 type, [percent] 
    FROM highest 
    WHERE ID = d.ID 
    ORDER BY [percent] DESC, type ASC 
) AS m 
GROUP BY d.ID, m.type, m.[percent] 
; 

也就是說,對於每個不同的ID,獲取具有最大值(TOP 1 ... ORDER BY [percent] DESCpercent的行。當多個類型對於相同ID具有最大值時,選擇其他類型之前排序的那個(type ASC)。

一個稍微不那麼冗長當量(使用DISTINCT,而不是GROUP BY):

SELECT DISTINCT d.ID, m.type, m.[percent] 
FROM highest AS d 
CROSS APPLY (
    SELECT TOP 1 type, [percent] 
    FROM highest 
    WHERE ID = d.ID 
    ORDER BY [percent] DESC, type ASC 
) AS m 
; 

有了適當的索引,不應該比@Bogdan Sahlean's suggestion更糟。