2017-06-29 156 views
2

我也有類似的錶行,各組與最低訂購組和特別的名字這如何獲得在SQL Server

CREATE TABLE [dbo].[Test](
    [Name] [NCHAR](10) NULL, 
    [GroupId] [INT] NULL, 
    [GroupOrder] [INT] NULL 
    ) 

及以下值

INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('A',1,1) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('A-1',1,2) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('B',2,1) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('B',2,2) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('B-1',2,3) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('C',3,1) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('C-1',3,2) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('C-1',3,3) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('D',4,1) 
INSERT INTO [dbo].[Test]([Name],[GroupId],[GroupOrder]) VALUES ('D',4,2) 

我需要這樣的輸出:行在具有最小訂單組和名稱字段的每個組中包含「-1」

Name GroupId GroupOrder 
    A-1   1 2 
    C-1   3 2 
    B-1   2 3 

回答

1

您可以使用此

Select * from 
(
select *,Row_Number() Over(Partition by GroupId Order by GroupOrder asc) as rn 
From yourtable 
Where Name like '%-1%' 
) a 
Where rn = 1 
1

使用ROW_NUMBER窗口函數

Select * from 
(
select *,Row_Number() Over(Partition by Name Order by GroupOrder asc) as rn 
From yourtable 
Where rtrim(Name) like '[A-Z]-1' 
) a 
Where rn = 1 

如果Name-1結束,然後使用Where Name like '%-1'。如果Name只包含-1然後Where Name like '%-1%'

+0

其中名稱是複製此答案由GroupId'有錯誤 – jozi

1
CREATE TABLE [dbo].[#Test](
    [Name] [NCHAR](10) NULL, 
    [GroupId] [INT] NULL, 
    [GroupOrder] [INT] NULL 
    ) 


INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('A',1,1) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('A-1',1,2) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('B',2,1) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('B',2,2) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('B-1',2,3) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('C',3,1) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('C-1',3,2) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('C-1',3,3) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('D',4,1) 
INSERT INTO [dbo].[#Test]([Name],[GroupId],[GroupOrder]) VALUES ('D',4,2) 

select * from #Test 

Select * from 
(
select *,Row_Number() Over(Partition by Name Order by GroupOrder asc) as rn 
From #Test 
Where Name like '%[-1]%' 
) a 
Where rn = 1 
ORDER BY GroupOrder 

輸出

Name GroupId GroupOrder 
A-1   1 2 
B-1   2 3  
C-1   3 2 
3

你可以使用charindextop 1 with ties,並row_number

select Top (1) with ties 
     * 
from Test t 
where charindex('-1', t.Name) > 0 
order by row_number() over(partition by t.GroupId order by t.GroupOrder) 

演示鏈接:http://rextester.com/RBBKX12749

+0

'分區最有可能。 – Serg

+0

感謝您的更正,@Serg – TriV