SQL 查看 Select 可选

SQL View Select Optional

我认为当前输出是这样的

   Code Value GrpCode GrpDft
  --------------------------
   A,   1,    A1,     N
   B,   null, A1,     Y
   C,   1,    A2,     N
   D,   2,    A2,     Y
   E,   null, A3,     Y
   F,   null, A3,     N       

规则如下

  1. 每个组只能有 2 个代码,并且始终有一个默认代码,而不是一个默认代码。
  2. 如果默认代码不为空,则始终显示该行。不管非默认代码是否有价值
  3. 如果默认代码为空,则仅当 none 默认代码值具有值时才显示它。
  4. 如果默认和非默认代码均为空,则显示默认值。

所以根据上面的内容,我应该还剩下下面一行。

   A, 1,    A1, N
   D, 2,    A2, Y
   E, null, A3, Y

不幸的是,由于其他因素,这必须作为视图而不是存储过程或函数来完成。

如果我没听错,您可以使用 window 函数实现该逻辑:

select * 
from (
    select 
        t.*,
        row_number() over(
            partition by grpCode
            order by 
                case
                    when grpDft = 'Y' and value is not null then 0
                    when grpDft = 'N' and value is not null then 1
                    else 2
                end,
                grpDft desc
        ) rn
    from mytable t
) t
where rn = 1

Demo on DB Fiddle:

Code | Value | GrpCode | GrpDft | rn
:--- | ----: | :------ | :----- | :-
A    |     1 | A1      | N      | 1 
D    |     2 | A2      | Y      | 1 
E    |  null | A3      | Y      | 1