SQL:如何根据不同的现有条件选择字段?

时间:2014-07-30 17:36:03

标签: sql postgresql select conditional-statements

我正面临一个SQL问题,该问题涉及根据特定条件选择行。下面的示例表称​​为' users'就像你:

id    category    label    date        rank count
111   weak        FFF      2014-06-01  1    4
111   strong      DDD      2014-06-02  2    4
111   strong      BBB      2014-06-03  3    4
111   weak        RRR      2014-06-04  4    4
222   weak        WWW      2014-07-01  1    3
222   weak        YYY      2014-07-02  2    3
222   weak        ZZZ      2014-07-03  3    3

有两个唯一ID(111222)。假设u.label下的所有值(如distinct ID中所示),我想检索每个users.category == 'weak'的最后一个ID 222

但是,如果'strong'下存在users.category,请返回u.label对应最新日期users.category == 'strong'

基本上,我正在寻找以下内容:

id    category    label    date      
111   strong      BBB      2014-06-03
222   weak        ZZZ      2014-07-03

我到目前为止所做的是使用"where rank=count"进行查询以获取最后一条记录,但我在如何选择u.label where category=='strong'给出最后一条记录时留下了空白是u.category=='weak'ID 111

谢谢,如果我能进一步澄清,请告诉我!

3 个答案:

答案 0 :(得分:2)

不需要窗口功能

select distinct on (id) id, category, dt
from t
order by id, category = 'weak', dt desc

SQL Fiddle

falsetrue之前排序,所以category = 'weak'排序最后

您可以将其他列添加到选择列表中。我只是重复使用@ mustaccio的小提琴,它没有label列。

检查distinct on

http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT

答案 1 :(得分:1)

这样的事情可能是:

select * from (
   select t.*, 
     row_number() over (
       partition by id 
       order by category asc, dt desc) rn
     from t
) tt where rn = 1;

SQLFiddle:http://sqlfiddle.com/#!1/475d49/1/0

答案 2 :(得分:1)

您最好的选择是使用row_number根据您的标准对记录进行排序,即按类别升序排序,然后按日期降序排序。

SELECT x.*
FROM (

    SELECT id, category, label, date, row_number() OVER (PARTITION BY id ORDER BY category ASC, date DESC) as ordinal_position
    FROM example
) x
WHERE ordinal_position = 1

SQL Fiddle