代码之家  ›  专栏  ›  技术社区  ›  DDS

选择“前1项”在出现“不返回值”的情况下不返回值

  •  0
  • DDS  · 技术社区  · 7 年前

    这是一个 link 我的数据。

    我有这个问题:

    SELECT *
    FROM tbl c
    WHERE C.dep = (select top 1 dep
                           from tbl cc
                           where cc.yea = c.yea
                           and cc.mon = mon
                           group by mon, yea, dep, n
                           order by n desc)
            OR C.dep =(     select top 1 dep
                                    from tbl cc
                                    where cc.yea = c.yea
                                    and cc.mon = mon
                                    group by mon, yea, dep, n
                                    order by n asc 
                                    )
    ORDER BY yea, mon, n
    

    每个人都应该回来 (month,year) 最佳(最低n)和最差(最高n) dep . 此查询适用于第1、2、4、5、7个月,而不适用于第3、6个月。唯一的区别是,在3个和6个案例中,我得到了两个得分相同的del(1)。我怎样才能归还其中一个,而不是不归还任何东西。

    这是我的输出:

    n           yea        mon        dep
    ----------- ----------- ----------- ----------
    1           2017        1           50
    48          2017        1           36
    58          2017        2           36
    85          2017        3           36
    1           2017        4           50
    39          2017        4           36
    1           2017        5           50
    39          2017        5           36
    19          2017        6           36
    3           2017        7           50
    17          2017        7           36
    

    这就是我所期望的:

    n           yea.        mon         dep
    ----------- ----------- ----------- ----------
    1           2017        1           50
    48          2017        1           36
    58          2017        2           36
    85          2017        3           36
    1           2017        3           49 (or 67)
    1           2017        4           50
    39          2017        4           36
    1           2017        5           50
    39          2017        5           36
    1           2017        6           50 (or 13)
    19          2017        6           36
    3           2017        7           50
    17          2017        7           36
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Gordon Linoff    7 年前

    使用 row_number() :

    select t.*
    from (select t.*,
                 row_number() over (partition by yea, mon order by n asc) as seqnum_asc,
                 row_number() over (partition by yea, mon order by n desc) as seqnum_desc
          from tbl t
         ) t
    where 1 in (seqnum_asc, seqnum_desc);