选择MAX(列值)的行,DISTINCT由SQL中的另一列选择

时间:2016-04-15 16:12:31

标签: sql max distinct

我有两张桌子,我有困难。 OrderHed& UD11。 OrderHed有1个值为OrderNum = 70960,但UD11有4个记录为70960。

我试图将UD11.Key5的最大值作为一个独特的记录返回 - 我做错了什么?

谢谢!

    SELECT TOP (100) PERCENT OrderHed.OrderNum,
    OrderHed.OpenOrder,
    OrderHed.OrderDate,
    OrderRel.Plant,
    OrderHed.EntryPerson,
    OrderHed.Company,
    Erp.Customer.CustID,
    Erp.Customer.NAME,
    Erp.InvcDtl.InvoiceNum,
    SUM(OrderDtl.ExtPriceDtl) AS Expr1,
    OrderHed.PONum,
    Ice.UD11.Key1,
    Ice.UD11.Key2,
    Ice.UD11.Key3,
    Ice.UD11.Key4,
    MAX(Ice.UD11.Key5) AS Expr2,
    Ice.UD11.Character01,
    Ice.UD11.Number01,
    Ice.UD11.Date01,
    Ice.UD11.Date02,
    Ice.UD11.Date03,
    Ice.UD11.ShortChar01,
    Ice.UD11.ShortChar02,
    Ice.UD11.ShortChar03,
    Ice.UD11.ShortChar04,
    Ice.UD11.ShortChar05,
    OrderHed.OrderComment
FROM Erp.Customer
RIGHT JOIN Ice.UD11
RIGHT JOIN Erp.OrderHed AS OrderHed ON Ice.UD11.Company = OrderHed.Company
    AND Ice.UD11.Key1 = OrderHed.OrderNum
LEFT JOIN Erp.OrderRel AS OrderRel
RIGHT JOIN Erp.OrderDtl AS OrderDtl ON OrderRel.Company = OrderDtl.Company
    AND OrderRel.OrderNum = OrderDtl.OrderNum
    AND OrderRel.OrderLine = OrderDtl.OrderLine ON OrderHed.Company = OrderDtl.Company
    AND OrderHed.OrderNum = OrderDtl.OrderNum ON Erp.Customer.Company = OrderHed.Company
    AND Erp.Customer.CustNum = OrderHed.CustNum LEFT JOIN Erp.InvcDtl RIGHT JOIN Erp.ShipDtl ON Erp.InvcDtl.Company = Erp.ShipDtl.Company
    AND Erp.InvcDtl.OrderNum = Erp.ShipDtl.OrderNum
    AND Erp.InvcDtl.OrderLine = Erp.ShipDtl.OrderLine
    AND Erp.InvcDtl.OrderRelNum = Erp.ShipDtl.OrderRelNum ON OrderRel.Company = Erp.ShipDtl.Company
    AND OrderRel.OrderNum = Erp.ShipDtl.OrderNum
    AND OrderRel.OrderLine = Erp.ShipDtl.OrderLine
    AND OrderRel.OrderRelNum = Erp.ShipDtl.OrderRelNum GROUP BY OrderHed.OrderNum,
    OrderHed.OrderDate,
    OrderRel.Plant,
    OrderHed.EntryPerson,
    OrderHed.Company,
    OrderHed.OpenOrder,
    Erp.Customer.CustID,
    Erp.Customer.NAME,
    Erp.InvcDtl.InvoiceNum,
    OrderHed.PONum,
    Ice.UD11.Key1,
    Ice.UD11.Key2,
    Ice.UD11.Key3,
    Ice.UD11.Key4,
    Ice.UD11.Character01,
    Ice.UD11.Number01,
    Ice.UD11.Date01,
    Ice.UD11.Date02,
    Ice.UD11.Date03,
    Ice.UD11.ShortChar01,
    Ice.UD11.ShortChar02,
    Ice.UD11.ShortChar03,
    Ice.UD11.ShortChar04,
    Ice.UD11.ShortChar05,
    OrderHed.OrderComment HAVING (OrderHed.Company = N'011')
    AND (Erp.InvcDtl.InvoiceNum IS NULL)
    AND (OrderHed.OrderNum = 70960)

1 个答案:

答案 0 :(得分:1)

SELECT  *
FROM    (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY OrderNum ORDER BY key5 DESC) rn
        FROM    (... /* my huge query */) q
        ) q
WHERE   rn = 1