2015-02-23 68 views
0

我是PostgreSQL和数据库查询的新手。仅在符合条件时才选择行

我有一个user_id列表,大学课程采取,日期开始和完成。 某些用户有多个条目,有时缺少开始日期或结束日期(或两者)。

我需要检索用户最长的课程,或者如果缺少开始日期,则需要检索最新的课程。 如果仍有多个选项可用,请在多个选项中随机选择。

例如

  • 用户2(下)我想只有“经济与政治”,因为它具有最新的日期;
  • 在用户6上,只有“电气和电子工程”,因为它是更长的路线。

我做不工作(我觉得我的脱轨)查询:

(SELECT Q.user_id, min(Q.started_at) as Started_on, max(Q.ended_at) as Completed_on, 
q.field_of_study 
    FROM 
    (select distinct(user_id),started_at, Ended_at, field_of_study 
    from educations 
    ) as Q 
    group by Q.user_id, q.field_of_study) 
    order by q.user_id 

的结果是:

User_id Started_on  Completed_on Field_of_studies 
    2  "2001-01-01" ""    "International Economics" 
    2  ""    "2002-01-01" "Economics and Politics" 
    3  "1992-01-01" "1999-01-01" "Economics, Management of ..." 
    5  "2012-01-01" "2016-01-01" "" 
    6  "2005-01-01" "2009-01-01" "Electrical and Electronics Engineering" 
    6  "2011-01-01" "2012-01-01" "Finance, General" 
    6  ""    ""    "" 
    6  "2010-01-01" "2012-01-01" "Financial Mathematics" 

回答

0

我觉得这个查询应该做的你需要什么,它依靠计算ended_at和started_at之间的天数差,并且如果started_at为空(使其为非常长的间隔),则使用0001-01-01

select 
    educations.user_id, 
    max(educations.started_at) started_at, 
    max(educations.ended_at) ended_at, 
    max(educations.field_of_study) field_of_study 
from educations 
join (
    select 
    user_id, 
    max( 
    ended_at::date 
    - 
    coalesce(started_at, '0001-01-01')::date 
) max_length 
    from educations 
    where (started_at is not null or ended_at is not null) 
    group by user_id 
) x on educations.user_id = x.user_id 
    and ended_at::date 
     - 
     coalesce(started_at, '0001-01-01')::date 
     = x.max_length 
group by educations.user_id 
; 

Sample SQL Fiddle

+0

谢谢@jpw!您的查询适用于大多数情况。但是它没有优先考虑最近一次相同课程的课程。用户9仍然显示2个课程,因为它们具有相同的长度:9;“”;“Katrinelund Gymnasium”;“1993-01-01”;“1996-01-01” 和-9;“”;“Birkbeck(University英国“;”2005-01-01“;”2008-01-01“ 在上面的例子中,我只需要显示2008年完成的一个。 – Marcello 2015-02-25 12:21:57

+0

@Marcello我已经更新了我的答案;它现在应该选择最新的课程,但是如果有几个课程的长度和日期相同,它应该选择“最高”的课程(以曲线图排序)。 – jpw 2015-02-25 13:21:24

+1

我添加了“独特”来防止重复,现在它完全可用。谢谢! – Marcello 2015-02-26 08:58:17

相关问题