DB2 Build特殊选择

jljoyd4f  于 2023-05-06  发布在  DB2
关注(0)|答案(1)|浏览(181)

我有一个多个主键IDANUMBER的表。
| ID(PK)|数量(PK)|名称|选项|
| --------------|--------------|--------------|--------------|
| 1| 1| A|真|
| 1|二|B|真|
| 1|三|C类|假的|
| 二|1| AA|真|
我想用Select得到的是
| ID(PK)|数量(PK)|名称|选项|
| --------------|--------------|--------------|--------------|
| 1| 1| A|真|

| ID(PK)|数量(PK)|名称|选项|
| --------------|--------------|--------------|--------------|
| 1|二|B|真|
我不知道是否有可能建立这样的Select
前提是ID应该相等,Optiontrue,并且返回哪一行并不重要,一行就足够了,这就是为什么我列出了上面两个有效的结果。

cpjpxq1n

cpjpxq1n1#

你可以使用group byhaving子句来实现,因为返回哪一行并不重要,你可以使用min()max()

select ID, MAX(ANUMBER) as ANUMBER, MAX(NAME) as NAME, 'true' AS OPTION
from mytable
where OPTION = 'true'
group by ID
having sum(case when OPTION = 'true' then 1 else 0 end) > 1

如果 OPTIONboolean,则尝试以下操作:

select ID, MAX(ANUMBER) as ANUMBER, MAX(NAME) as NAME, 'true' AS OPTION
from mytable
where OPTION
group by ID
having sum(case when OPTION then 1 else 0 end) > 1

如果你不想列出所有的列,你可以使用窗口函数row number()和累积sum()

with cte as (
  select *, row_number() over(partition by id order by ANUMBER desc) rn, 
            sum(case when OPTION then 1 else 0 end) over(partition by id order by ANUMBER ROWS UNBOUNDED PRECEDING) as count_
  from mytable
  where OPTION
)
select *
from cte c
where rn = 1 and COUNT_ > 1

Demo here

相关问题