SQL Server Trying to get the latest ID and one unique name from SQL

pn9klfpd  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(87)

I need to get the Sectionname and SectionId from SectionNomination table. I need to combine the SectionId to get the last section and only one SectionName .

So from this table:

I need to get one testSection1 and one TestSection3 with one section ID which is 35. Same thing with TestSection3 , I want to get sectionID = 37 .

I wrote this query to achieve this:

select  
    SectionName, SectionId
from 
    testTable pt, 
    (select max(SectionId) as pID 
     from testTable 
     group by SectionID) st
where 
    pt.SectionID = st.pID

This is not returning the max ID and also returning the duplicates.

Here is the sample data:

INSERT INTO [dbo].[testTable] ([SectionName])
VALUES ('TestSection1')

INSERT INTO [dbo].[testTable] ([SectionName])
VALUES ('TestSection2')

sectionId is an Identity column.

Create table is this SQL statement:

CREATE TABLE [dbo].[testTable]
(
    [SectionID] [int] IDENTITY(1,1) NOT NULL,
    [SectionName] [varchar](1000) NULL,
    
    CONSTRAINT [PK_SectionNomination] 
        PRIMARY KEY CLUSTERED ([SectionID] ASC)
)
jfewjypa

jfewjypa1#

All you need is...

SELECT
    s.SectionName,
    MAX( s.SectionId ) AS MaxSectionId
FROM
    dbo.TestTable AS s
GROUP BY
    s.SectionName
ORDER BY
    SectionName;
SectionNameMaxSectionId
TestSection135
TestSection337
TestSection438

DbFiddle

相关问题