按计数psql按类型顺序合并行

时间:2015-05-26 19:21:42

标签: sql postgresql

我有Elements表:

id entity_type likes_count
1     Part        20
2     Ride        10
3     Part        11
4     Profile     12
5     Part        11
6     Part        30
7     Ride        14
8     Part        12
9     Profile     10
10    Part        8

所以我需要sql语句,它通过Ride,Part,Profile(intercalate)和like count desc返回元素顺序。

结果将是:

id entity_type likes_count
7     Ride        14
6     Part        30
4     Profile     12
2     Ride        10
1     Part        20
9     Profile     10
8     Part        12
3     Part        11
5     Part        11
10    Part        8

我有(PostgreSQL)9.4.1。谢谢!!!

1 个答案:

答案 0 :(得分:0)

试试这个。

select id,entity_type,likes_count from 
(
SELECT Row_number()OVER (partition BY entity_type ORDER BY likes_count DESC)rn,id,entity_type,likes_count
FROM   elements
) A
ORDER  BY rn,
          CASE entity_type
            WHEN 'Ride' THEN 1
            WHEN 'Part' THEN 2
            ELSE 3
          END