gpt4 book ai didi

sql - 有什么方法可以避免此 Oracle 查询中出现联合吗?

转载 作者:行者123 更新时间:2023-12-02 09:32:29 25 4
gpt4 key购买 nike

我有一个这样的表:

+-------+--------------+--------------+-------------+-------------+-------------+-------------+
| Study | Point_number | Date_created | condition_A | condition_B | condition_C | condition D |
+-------+--------------+--------------+-------------+-------------+-------------+-------------+
| 1 | 1 | 01-01-2001 | 1 | 1 | 0 | 1 |
| 1 | 2 | 01-01-2001 | 0 | 1 | 1 | 0 |
| 1 | 3 | 01-01-2001 | 0 | 1 | 0 | 0 |
+-------+--------------+--------------+-------------+-------------+-------------+-------------+

条件_A、B、C 和 D 用于将数据点分类。因此,这些列的每个独特组合都将是一个组。对于每个组,我想检索最后 200 行。

目前我有这样的事情:

select * from my_table where point_number <= 200;

为了对每个组执行此操作,我可以这样做:

select * from my_table where point_number <= 200 where condition_A = 1 and condition_B = 1 and condition_C = 1 and condition D = 1
union all
select * from my_table where point_number <= 200 where condition_A = 1 and condition_B = 1 and condition_C = 1 and condition D = 0
union all...;

这种方法的问题是有很多很多组合,最好让查询尽可能灵活。如何避免执行 UNION ALL 并使查询自动检索每个组的 200 行?

最佳答案

您的原始查询:

select *
from my_table
where point_number <= 200;

应该执行您想要的操作 - 检索小于 200 的 point_number 值。它应该为每个组执行此操作。

如果您希望每个组中有 200 个值,那么您真正想要的可能是这样的:

select t.*
from (select t.*,
row_number() over (partition by a, b, c, d order by point_number desc) as seqnum
from my_table
) t
where seqnum <= 200;

这假设 point_number() 正在增加,并且较大的值是“较新的”。您可能希望在 order by 中使用 date_created,而不是 point_number

关于sql - 有什么方法可以避免此 Oracle 查询中出现联合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31404556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com