如何按不同或组排序?

时间:2013-11-25 13:45:37

标签: sql postgresql group-by distinct

我有一个表'items'(超过1,000,000行),12列:

id | name | group_id | cost   | column5 | column6 | column7 | column8 | column9 | column10 | column11 | column12
1  | A1   | 100      | 10,00  | c_15    | c_16    | c_17    | c_18    | c_19    | c_110    | c_111    | c_112
2  | A2   | 300      | 17,00  | c_25    | c_26    | c_27    | c_28    | c_29    | c_210    | c_211    | c_212
3  | A3   | 200      | 16,24  | c_35    | c_36    | c_37    | c_38    | c_39    | c_310    | c_311    | c_312
4  | A4   | 100      |  8,01  | c_45    | c_46    | c_47    | c_48    | c_49    | c_410    | c_411    | c_412
5  | A5   | 100      | 19,62  | c_55    | c_56    | c_57    | c_58    | c_59    | c_510    | c_511    | c_512
6  | A6   | 400      | 10,00  | c_65    | c_66    | c_67    | c_68    | c_69    | c_610    | c_611    | c_612
7  | A7   | 200      | 16,22  | c_75    | c_76    | c_77    | c_78    | c_79    | c_710    | c_711    | c_712
8  | A8   | 300      |  7,00  | c_85    | c_86    | c_87    | c_88    | c_89    | c_810    | c_811    | c_812

如何为该group_id获取具有唯一group_id和最低成本的行,并为任何列(name,column5,column6等)排序?

例如,为第5列排序:

id | name | group_id | cost   | column5 | column6 | column7 | column8 | column9 | column10 | column11 | column12
4  | A4   | 100      |  8,01  | c_45    | c_46    | c_47    | c_48    | c_49    | c_410    | c_411    | c_412
6  | A6   | 400      | 10,00  | c_65    | c_66    | c_67    | c_68    | c_69    | c_610    | c_611    | c_612
7  | A7   | 200      | 16,22  | c_75    | c_76    | c_77    | c_78    | c_79    | c_710    | c_711    | c_712
8  | A8   | 300      |  7,00  | c_85    | c_86    | c_87    | c_88    | c_89    | c_810    | c_811    | c_812

例如按成本排序:

id | name | group_id | cost   | column5 | column6 | column7 | column8 | column9 | column10 | column11 | column12
8  | A8   | 300      |  7,00  | c_85    | c_86    | c_87    | c_88    | c_89    | c_810    | c_811    | c_812
4  | A4   | 100      |  8,01  | c_45    | c_46    | c_47    | c_48    | c_49    | c_410    | c_411    | c_412
6  | A6   | 400      | 10,00  | c_65    | c_66    | c_67    | c_68    | c_69    | c_610    | c_611    | c_612
7  | A7   | 200      | 16,22  | c_75    | c_76    | c_77    | c_78    | c_79    | c_710    | c_711    | c_712

3 个答案:

答案 0 :(得分:0)

您可以使用ROW_NUMBER()功能:

select * from
(
select *,
ROW_NUMBER() 
      OVER
     (PARTITION BY group_id  order by cost) as rn
from items
) as i  
where i.rn=1
order by column5

SQLFiddle demo

答案 1 :(得分:0)

PostgreSQL有一个特殊的语法 - distinct on

with cte as (
    select distinct on (group_id)
        *
    from Table1
    order by group_id, cost
)
select *
from cte
order by column5

我不建议在制作中使用*,这里我只是为了简化代码而使用它。

答案 2 :(得分:0)

使用

with cte as (
    select distinct on (group_id) id, column5
    from prices
    order by group_id, cost
)
select id
from cte
order by column5

与1-2列完美配合