按自定义条件对SQL结果进行分组

时间:2015-12-03 12:10:34

标签: sql postgresql

我希望使用 key_id = 1 获取图片,或者 key_id = null

id | image                  | key_id 
----------------------------------
12 | default_thumbnail      | null  
12 | Abrams.png             | 1
14 | default_thumbnail      | null  
15 | default_thumbnail      | null  
15 | T34.png                | 1
15 | T34-big.png            | 3 
16 | T31.png                | 3 

要达成的结果:

id | image                  | key_id 
----------------------------------
12 | Abrams.png             | 1
14 | default_thumbnail      | null  
15 | T34.png                | 1

我浪费了很多时间,但我无法解决这个问题...

3 个答案:

答案 0 :(得分:1)

这是一种方法:

select *
from t
where key_id = 1
union all
select *
from t
where key_id is null and 
      not exists (select 1 from t t2 where t2.id = t.id);

也可以使用row_number()为每个id选择一行以确定优先级:

select t.*
from (select t.*,
             row_number() over (partition by id
                                order by key_id nulls last
                               ) as seqnum
      from t
      where key_id is null or key_value = 1
     ) t
where seqnum = 1;

答案 1 :(得分:1)

array_agg()的解决方案:

select 
    id, 
    (array_agg(image))[1] image, 
    (array_agg(key_id))[1] key_id
from (
    select * 
    from a_table
    where key_id = 1 or key_id is null
    order by key_id nulls last
    ) s
group by 1
order by 1;

 id |       image       | key_id 
----+-------------------+--------
 12 | Abrams.png        |      1
 14 | default_thumbnail |       
 15 | T34.png           |      1
(3 rows)

答案 2 :(得分:0)

当进行分组时,你还需要指定如何选择如何处理每个字段,当有两个名为default_tumbnail的图像并将它们组合在一起时,如果SQL显示第一个的key_id,或者第二个?

因此,您可以选择每列的最小值(或最大值),也可以按它们分组以分隔所有内容。

下面的示例将为您提供每个图像名称的第一个ID和第一个Key_ID。

Select min(ID) as FirstID, min(key_id) as FirstKeyID from YourTableName where (key_id = 1) or (key_id is null)
Group by image