如何在db2 Sql中对每列不包含空值的记录进行汇总?

nx7onnlm  于 2022-11-29  发布在  DB2
关注(0)|答案(1)|浏览(137)

我有一个表如下-
| 标识符|姓名|列1|第2列|第3列|
| - -| - -| - -| - -| - -|
| 一个|美国汽车协会|一个|零值|零值|
| 一个|美国汽车协会|零值|一个|零值|
| 一个|美国汽车协会|零值|零值|一个|
| 一个|美国汽车协会|零值|零值|2个|
| 一个|美国汽车协会|零值|一个|零值|
| 2个|bbb的复数|零值|零值|零值|
| 2个|bbb的复数|一个|零值|零值|
我希望输出如下-
| 标识符|姓名|列1|第2列|第3列|
| - -| - -| - -| - -| - -|
| 一个|美国汽车协会|一个|一个|一个|
| 一个|美国汽车协会|零值|一个|2个|
| 2个|bbb的复数|一个|零值|零值|
我试着这样做:

select id ,name, max(col1),max(col2),max(col3) 
from table group by id, name;

但输出是这样的,这不是预期的
| 标识符|姓名|列1|第2列|第3列|
| - -| - -| - -| - -| - -|
| 一个|美国汽车协会|一个|一个|2个|
你能帮我达到预期的产量吗?非常感谢。

toe95027

toe950271#

您可以按原样试用。
首先,由指定的每个组中的行(id,name)列。请注意,如果在row_number函数中不使用order by子句,(如示例中所示),这样的枚举可能以某种不可重复和不可预测的方式完成。因此,如果您希望得到可重复的结果,您应该有一种方法来显式地对行进行排序。我添加了一个附加行,您可以使用它取消对orderby子句的注解,以获得您在问题中指定的确切结果。
然后,使用递归公用表表达式语句处理每个组中的行。(每组内附加组号)引入.每组的第一行(rn_= 1)获取所有原始值且grp = 1。如果c1的值并且相应列的前一行中的值也非空。
如果组号不增加,则复制前一行的非空值,而不是每个cx的当前值。
如果增加,则保留当前行的值。
最后,我们在groupby子句中使用此代理组编号。
dbfiddle link

with mytab (id, name, c1, c2, c3, ord) as
(
values
  (1, 'aaa', 1, null::int, null::int, 10)
, (1, 'aaa', null, 1, null, 20)
, (1, 'aaa', null, null, 1, 30)
, (1, 'aaa', null, null, 2, 40)
, (1, 'aaa', null, 1, null, 50)
, (2, 'bbb', null, null, null, 1)
, (2, 'bbb', 1, null, null, 2)
)
-- Rows enumeration inside all groups
, mytab2 as 
(
select row_number () over (partition by id, name
--order by ord
) rn_, t.*
from mytab t
)
--
, a (id, name, rn_, grp, c1, c2, c3) as
(
select id, name, rn_, 1 as grp, c1, c2, c3 
from mytab2
where rn_ = 1
  union all
select t.id, t.name, t.rn_
, a.grp 
+ case 
    when a.c1 is not null and t.c1 is not null
      or a.c2 is not null and t.c2 is not null
      or a.c3 is not null and t.c3 is not null
    then 1
    else 0
  end as grp
, case 
    when a.c1 is not null and t.c1 is not null
      or a.c2 is not null and t.c2 is not null
      or a.c3 is not null and t.c3 is not null
    then t.c1
    else coalesce (a.c1, t.c1)
  end as c1
, case 
    when a.c1 is not null and t.c1 is not null
      or a.c2 is not null and t.c2 is not null
      or a.c3 is not null and t.c3 is not null
    then t.c2
    else coalesce (a.c2, t.c2)
  end as c2
, case 
    when a.c1 is not null and t.c1 is not null
      or a.c2 is not null and t.c2 is not null
      or a.c3 is not null and t.c3 is not null
    then t.c3
    else coalesce (a.c3, t.c3)
  end as c3
from a, mytab2 t
where t.id = a.id and t.name = a.name and t.rn_ = a.rn_ + 1
)
select id, name
, max (c1) as c1
, max (c2) as c2
, max (c3) as c3
from a
group by id, name, grp

相关问题