有一个表,字段为Category,Name,Value,Number。除了Value是int类型外,其它都是varchar(50)。
可能数据为:
- SQL code
/*Category Name Value Number分类1 A 1 A-001分类1 A 2 A-002分类1 A 3 A-102分类1 B 1 A-082分类1 A 2 A-003分类1 A 3 A-002分类1 A 1 A-002*/
现在我需要这样的数据
- SQL code
/*Category Name Value Number分类1 A 1 A-001分类1 A 1 A-002分类1 A 2 A-003分类1 B 1 A-082分类1 A 3 A-102*/
即Number有相同的编号时,只取Value为最小值的那条数据,并为Number列升序排列。
请问如何用SQL语句实现?最好给出可运行语句,谢谢!
------解决方案--------------------
- SQL code
select Category,[Name],[Value],Number from t where t.[Value]=(select min([Value]) from t t1 where t.Category=t1.Category and t.[Name]=t1.[Name] and t.[Number]=t1.[Number]) order by t.Number--t为你的表
------解决方案--------------------
- SQL code
--> 测试数据:[test]if object_id('[test]') is not null drop table [test]gocreate table [test]([Category] varchar(5),[Name] varchar(1),[Value] int,[Number] varchar(5))goinsert [test]select '分类1','A',1,'A-001' union allselect '分类1','A',2,'A-002' union allselect '分类1','A',3,'A-102' union allselect '分类1','B',1,'A-082' union allselect '分类1','A',2,'A-003' union allselect '分类1','A',3,'A-002' union allselect '分类1','A',1,'A-002'goselect [Category], [Name], [Value], [Number]from (select px=ROW_NUMBER()over(partition by [Number],[Name],[Category] order by [Value]),*from test )twhere px=1/*Category Name Value Number分类1 A 1 A-001分类1 A 1 A-002分类1 A 2 A-003分类1 B 1 A-082分类1 A 3 A-102*/