仅显示具有分区依据的最大行的值?

Only show value of Max rows with partition by?

标题可能有点偏离,但我试图在不删除实际行的情况下删除一行的值。

这是我的table:

SELECT ID,CustomerID,Weight FROM Orders

我要完成的是:

ID Group By CustomerIDMAX() 值会在 [=13] 中给出空值=] 其中 max 和 group by 未设置

是否可以一行完成?用 partiton by?

类似于:

SELECT MAX(ID) over (partition by CustomerID,Weight).... 我知道这是错误的,但如果可能的话,不使用连接或 CTE,并且只在 select 语句中的一行,那会很棒。

试试这个

;WITH CTE
AS
(
    SELECT
        MAX_ID = MAX(ID) OVER(PARTITION BY CustomerId),
        ID,
        CustomerId,
        Weight
        FROM Orders
)
SELECT
    ID,
    CustomerId,
    Weight = CASE WHEN ID = MAX_ID THEN Weight ELSE NULL END
    FROM CTE

你可以试试这个。

SELECT ID,CustomerId,CASE WHEN ID= MAX(ID) OVER(PARTITION BY CustomerId) THEN Weight ELSE NULL END AS Weight FROM Orders

一种可能的方法是使用 ROW_NUMBER:

SELECT 
    ID,
    CustomerID,
    CASE 
        WHEN ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY ID DESC) = 1 THEN [Weight]
        ELSE Null
    END AS [Weight]
FROM #Orders
ORDER BY ID

输入:

CREATE TABLE #Orders (
    ID int,
    CustomerID int,
    [Weight] int
)
INSERT INTO #Orders
    (ID, CustomerID, [Weight])
VALUES
    (1, 11, 100),
    (2, 11, 17),
    (3, 11, 35),
    (4, 22, 26),
    (5, 22, 78),
    (6, 22, 10030)

输出:

ID  CustomerID  Weight
1   11          NULL
2   11          NULL
3   11          35
4   22          NULL
5   22          NULL
6   22          10030