每个城市的最近一年和项目

时间:2015-04-17 12:14:13

标签: mysql

我有两张桌子。一个有市政当局(wsjg_mun),另一个有项目(wsjg_proj)。我需要每个城市最近一年(yr)和项目(proj_id)。

Table wsjg_mun (municipalities)

    pol_id (hash version of municipality name)
    mun (municipality name)
    cbs_cde
    cbs_id (municipality id, PK)

Table wsjg_proj (projects)

    cbs_id (municipality id)
    yr (year project)
    edition
    proj_id (project)
    lud

此查询

SELECT a.pol_id, a.mun, a.cbs_cde, a.cbs_id,  yr, b.edition FROM wsjg_proj b   
LEFT JOIN wsjg_mun a 
ON a.cbs_id = b.cbs_id
GROUP BY b.cbs_id, b.yr
ORDER BY  b.cbs_id , b.yr asc

结果:

Bedum     2010  BP
Bedum     2011  BR
Bedum     2014  BP  
Ten Boer  2011  BR
Ten Boer  2013  BP

我想

Bedum     2014  BP  
Ten Boer  2013  BP

2 个答案:

答案 0 :(得分:1)

您作为示例提供的输出与查询不匹配,但无论如何,我认为您正在寻找的内容是这样的:

select a.mun, b.edition, b.yr
from wsjg_mun a 
join wsjg_proj b on a.cbs_id = b.cbs_id
join (
    select cbs_id, max(yr) as max_yr
    from wsjg_proj
    group by cbs_id
) max_proj_yr on b.cbs_id = max_proj_yr.cbs_id and max_proj_yr.max_yr = b.yr

用作派生表的查询确定每个cbs_id的最新年份。

答案 1 :(得分:1)

我认为像这样的查询会很有用:

SELECT a.mun, b.yr, b.edition
FROM wsjg_mun a
  LEFT JOIN wsjg_proj b ON a.cbs_id = b.cbd_id
WHERE b.yr = (
        SELECT Max(bi.yr) 
        FROM wsjg_proj bi
        WHERE bi.cbs_id = b.cbs_id)