简体   繁体   中英

SQL Server : Select max with Sub-select

I am try to get a max value of a result set of another select in SQL Server, but not able to. I am not sure what I am doing incorrect in SQL Server. Any help would be great.

This is my SQL:

select 
    max(A.ID), A.Name, A.RMName, A.RName, A.DName, A.Section, A.CF, A.PPV, A.ESD,
    A.EED, A.EJ, 
    A.NJ, A.NAF, A.L4MAF, A.L4MJ, A.MLF, A.PL, A.PN, A.EMSFL, A.PV, A.FName, 
    A.FLevel, A.SC, A.PID, A.PFID 
from (
        select distinct 
            ID, Name, RMName, RName, DName, Section, CF, PPV,
            REPLACE(CONVERT (VARCHAR, ESD, 6), ' ', '-') ESD,
            REPLACE(CONVERT (VARCHAR, EED, 6), ' ', '-') EED,
            REPLACE(REPLACE(REPLACE(EJ, CHAR(10), ''), CHAR(13), ''), CHAR(9), '') as EJ,
            REPLACE(REPLACE(REPLACE(NJ,CHAR(10), ''), CHAR(13), ''), CHAR(9), '') as NJ,
            NAF,
            L4MAF,
            REPLACE(REPLACE(REPLACE(L4MJ,CHAR(10), ''), CHAR(13), ''), CHAR(9), '') as L4MJ,
            MLF,
            PL,
            PN,
            EMSFL,
            PV,
            FName,
            FLevel,
            SC,
            PID,
            PFID
        from 
            dbo.DFD def (nolock),
            dbo.DForm form (nolock),
            dbo.DExcp exc (nolock)
        where 
            exc.DPID = def.DFDID
            and def.DFID = form.DFID
            and NAF = 1
            and L4MAF = 1
            and RMName is not null
            and EED >= GETDATE()
            and EED <> '2050-01-01 00:00:00.000') as A
group by 
     Name, RMName, RName, DName, Section, CF, 
     PPV, ESD, EED, EJ, NJ, NAF, L4MAF, L4MJ, 
     MLF, PL, PN, EMSFL, PV, FName, FLevel, 
     SC, PID, PFID

While your question is somewhat unclear. I'll give you a an example based on what I think you're asking

Get all Rows that have Id = to Max Id

SELECT
   b.*
FROM
   (SELECT MAX(Id) AS [MaxId] From MyTable) a INNER JOIN
   MyTable b ON a.MaxId = b.Id

There are other ways to do this but this will give you all rows in your table that have an Id equal to the maximum id in your table. I can tailor a more specific example if I have misunderstood what you're getting at.

-Ben

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM