列出删除表的年份

时间:2014-09-14 13:43:18

标签: sql oracle

如果我有这些表格:

SUMMERGAMES (sg_gameno [PK], sg_year) 
GAME-DISCIPLINE ( discipline_code[PFK], sg_gameno[PFK] )
DISCIPLINE (discipline_code, discipline_name)

我需要列出2004年运行但未在2008年或2012年运行的那些学科的学科代码和学科名称。我还需要列出它被删除的年份,即(2008年或2012年)第一年它没有出现。

我使用MINUS运算符来解决第一部分。但我不知道如何列出掉落的那一年。

1 个答案:

答案 0 :(得分:1)

如何使用聚合并获得最大年份的东西,以及它是否在2004年左右?

select d.discipline_code, d.displine_name,
       max(sg.sg_year) as lastYearRan,
       max(sg.sg_year) + 4 as firstYearDropped
from summergames sg join
    gamediscipline gd
    on sg.sg_gameno = gd.sg_gameno join
    discipline d
    on gd.discipline_code = d.discipline_code
group by d.discipline_code, d.displine_name
having sum(case when sg.sg_year = 2004 then 1 else 0 end) > 0 and
       sum(case when sg.sg_year in (2008, 2012) then 1 else 0 end) = 0;

having子句有两个条件。第一个说这个纪律是在2004年进行的。第二个说它没有在2012年运行 - 所以可能在2008年或2012年下降。

having子句中的每个条件都计算匹配行的数量。例如,第一个条件是计算2004年的行数。> 0要求至少有一个。类似地,第二个计算纪律具有2008年或2012年的行数。= 0要求没有这样的记录。

相关问题