2015-09-01 75 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是表示例中使用的别名。