有没大神帮忙解决一个SQL去重+查询+排序+取最小值的问题

xcdel 2016-04-11 03:54:12
表A三个列 ID,Type,Data,三个列都得获取。
以Type去重并获取最小的Data,可是查询要带上ID。
group by带上 ID的话做不到去重,可是不带ID的话select ID 就报错。这里怎么写?
这是第一步。

然后根据Type的值(可能是1、2、3或者2、1、3什么的不规则的顺序),由上往下只查询一条数据。
这是第二步。

最好两步一个SQL语句,不行的话两个SQL语句也行。
...全文
306 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
道素 2016-04-11
  • 打赏
  • 举报
回复

declare @tb table(ID int,[Type] int,[Data] int)
insert into @tb(ID,[Type],[Data])
select * from  (
	select 1,1,16436 union all
	select 2,2,2345 union all
	select 3,3,2154 union all
	select 4,1,143 union all
	select 5,1,5 union all
	select 6,2,74 union all
	select 7,2,542 union all
	select 8,1,623 union all
	select 9,3,5123
) t(ID,[Type],[Data])
select * from @tb
delete t1 from @tb as t1
inner join 
(
select *,row_number()over(partition by [type] order by [data] desc) as SeqNo from @tb
) t2 on t2.id=t1.id and t2.SeqNo!=1
select * from @tb

删除前:
/*
ID	Type	Data
1	1	16436
2	2	2345
3	3	2154
4	1	143
5	1	5
6	2	74
7	2	542
8	1	623
9	3	5123
*/
删除后:
/*
ID	Type	Data
1	1	16436
2	2	2345
9	3	5123
*/
xcdel 2016-04-11
  • 打赏
  • 举报
回复
引用 2 楼 spiritofdragon 的回复:
with t(id,Type,data) as (
select 1,1,16436 union all
select 2,2,2345 union all
select 3,3,2154 union all
select 4,1,143 union all
select 5,1,5 union all
select 6,2,74 union all
select 7,2,542 union all
select 8,1,623 union all
select 9,3,5123
)
select id,Type,data 
from (
	select *
		,ROW_NUMBER()over(partition by type order by data)rn
	from t
	) tt
where tt.rn=1
	
谢谢大神,第一步搞定了,第二步我来遍历吧
唐诗三百首 2016-04-11
  • 打赏
  • 举报
回复
第一步如下代码,第二步看不懂,请再说明.

select a.*
  from 表A a
  where not exists(select 1 from 表A b where b.Type=a.Type and b.Data<a.Data)
spiritofdragon 2016-04-11
  • 打赏
  • 举报
回复
with t(id,Type,data) as (
select 1,1,16436 union all
select 2,2,2345 union all
select 3,3,2154 union all
select 4,1,143 union all
select 5,1,5 union all
select 6,2,74 union all
select 7,2,542 union all
select 8,1,623 union all
select 9,3,5123
)
select id,Type,data 
from (
	select *
		,ROW_NUMBER()over(partition by type order by data)rn
	from t
	) tt
where tt.rn=1
	

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧