简体   繁体   English

SQL Server:通过子选择选择最大

[英]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. 我试图在SQL Server中获得另一个选择的结果集的最大值,但无法这样做。 I am not sure what I am doing incorrect in SQL Server. 我不确定我在SQL Server中做错了什么。 Any help would be great. 任何帮助都会很棒。

This is my SQL: 这是我的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 获取所有具有Id =到最大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. 还有其他方法可以执行此操作,但这将为您提供表中所有ID等于表中最大ID的行。 I can tailor a more specific example if I have misunderstood what you're getting at. 如果我误解了您的意思,我可以定制一个更具体的示例。

-Ben -本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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