2015-09-01 134 views
1

我需要找到各組的最高估值的行的表,例如在,我想組由顏色和形狀以下,然後取最高成本的行。例如。輸入返回排名最高的行每組

ID Color Shape Cost 
-- ----- ----- ---- 
1 Red Round 45 
2 Red Round 18 
3 Red Square 13 
4 Red Square 92 
5 Green Round 25 
6 Green Round 21 
7 Green Triangle 20 
8 Green Triangle 33 

我想

ID Color Shape Cost 
-- ----- ----- ---- 
1 Red Round 45 
4 Red Square 92 
5 Green Round 25 
8 Green Triangle 33 

我怎樣才能做到這一點?對PL/SQL和T/SQL起作用的東西會非常棒,儘管我的直接需求是PL/SQL。

回答

4

您可以使用row_number分區上的顏色和形狀,然後分配1的行號在該分區中成本最高。

select id,color,shape,cost 
from 
(
select *, 
row_number() over(partition by color,shape order by cost desc) as rn 
from tablename 
) t 
where rn = 1; 
0

如果你正在尋找一個真正的基本解決方案,那麼你最好的選擇是在下面。這可以在幾乎所有的SQL變體中使用。

而且無論你相信與否,這是更快的對快閃「ROW_NUMBER()」版本。 但我們正在談論微秒。所以它只是一個偏好問題。

下面

DECLARE @Data TABLE (ID INT,Colour NVARCHAR(16),Shape NVARCHAR(16),Cost INT) 
INSERT INTO @Data 
VALUES 
(1,'Red' ,'Round', 45), 
(2,'Red' ,'Round', 18), 
(3,'Red' ,'Square', 13), 
(4,'Red' ,'Square', 92), 
(5,'Green','Round', 25), 
(6,'Green','Round', 21), 
(7,'Green','Triangle',20), 
(8,'Green','Triangle',33) 

SELECT  D.ID, 
      D.Colour, 
      D.Shape, 
      G.Cost 
FROM  @Data AS D 
INNER JOIN 
(
    SELECT  Colour,Shape,MAX(Cost) AS Cost 
    FROM  @Data 
    GROUP BY Colour,Shape 
) AS G ON G.Colour = D.Colour AND G.Shape = D.Shape AND G.Cost = D.Cost 
0

工作示例這應該是一個簡單的SELECT語句,如果你有你的表設置 - 我們將稱之爲TABLE_A:

SELECT id, color, shape, max(cost) as Cost 
from table_a 
group by id, color, shape 

不能確定輸出允許成本將在您的輸出中大寫 - 有時這取決於您的SQL語法。

+0

在GROUPBY的ID表示這是不行的。檢查預期的結果 –

0

這也可以使用共相關子查詢完成的,(在IMPALA SQL例如是不可能的)如下所示:

select id,color,shape,cost 
from ex_1 a where cost = (select max(cost) 
         from ex_1 b 
         where a.shape = b.shape 
         and a.color = b.color) 

我命名的表作爲具有ex_1 8項和a,b是表示例中使用的別名。