SQL查询所有数据,过滤掉某字段值重复的行

这么个表,有3个字段(id, name, age),其中id是主键,name和age允许重复:

CREATE TABLE t_user (
"id"   int4 NOT NULL,
"name" varchar ,
"age"  int4,
PRIMARY KEY ("id")
);

INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('1', 'jim', '20');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('2', 'lily', '18');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('3', 'lucy', '18');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('4', 'jim', '21');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('5', 'jim', '22');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('6', 'lily', '17');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('7', 'hanmeimei', '16');
INSERT INTO "public"."t_user" ("id", "name", "age") VALUES ('8', 'jim', '22');

完整测试数据如下图:



1. 获取所有数据,其中相同的name只出现一次:

select * from t_user 
where id in (
	select min(id) from t_user
	where 1 = 1 
	group by name
);

2. 获取所有数据,其中相同的name只出现一次,且age是相同的name中最大的:

select * from t_user 
where id in (
	select min(c.id) from (
		select b.* from (
			select name, max(age) as max_age from t_user
			where 1 = 1 
			group by name
		) a 
		left join t_user b on (b.name = a.name and b.age = a.max_age)
	) c
	group by c.name
);


3. 同理,可以实现删除重复行(某字段值重复)

delete from t_user 
where id not in (
	select min(id) from t_user
	where 1 = 1 
	group by name
);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值