仅获取满足条件的前 N ​​行,但保留不满足条件的行

时间:2021-04-28 13:50:16

标签: sql postgresql

<头>
id 类型
1 身体
2 body1
3 身体
4 body1
5 body1
6 body1
7 身体
8 body1
9 body1
10 身体

是否可以选择 typebody 的前 3 行,但保留 type 不等于 body 的其他行?预期结果是 id 为 1 到 7 的行。

4 个答案:

答案 0 :(得分:1)

您似乎想要第三个 Microsoft.EntityFrameworkCore.SqlServer 之前的所有内容。一种方法是:

body

注意:此特定公式假设至少有三行 select t.* from t where t.id <= (select t2.id from t t2 where t2.type = 'body' order by t2.id limit 1 offset 2 ); 。它可以进行调整,但这与您的示例数据一致。

答案 1 :(得分:0)

这是您要找的吗?

'body'

ORDER BY 将确保您选择按 id 列排序的顶部行

LIMIT 3 将只选择前 3 个结果

答案 2 :(得分:0)

另一种解决方案是使用排名

复制你的表格
create table test_body (id integer, str_type varchar);
insert into test_body values(1, 'body');
insert into test_body values(2, 'body1');
insert into test_body values(3, 'body');
insert into test_body values(4, 'body1');
insert into test_body values(5, 'body1');
insert into test_body values(6, 'body1');
insert into test_body values(7, 'body');
insert into test_body values(8, 'body1');
insert into test_body values(9, 'body1');
insert into test_body values(10, 'body');

下面的查询计算条件的排名,然后用它来过滤数据

with ranking_sel as(
select *, 
case when str_type = 'body' then 1 else 0 end condition,
rank() over (partition by case when str_type = 'body' then 1 else 0 end order by id) rnk from test_body 
)

select * from ranking_sel where rnk <= 3 or condition = 0 order by id;

答案 3 :(得分:0)

你需要使用窗口函数DENSE_RANK()

SELECT
*
FROM
(
    SELECT
        DENSE_RANK() OVER (PARTITION BY t1.type ORDER BY t1.id) rnk,
        t1.*
    FROM table t1
) t2
WHERE
 (t2.type = 'body' and rnk <= 3) or (t2.type != 'body')