我有一张这样的表:
Loan_Num asset LTV
1 20 0.2
2 20 0.2
3 20 0.12
4 20 0.2
5 10 0.3
6 10 0.3
7 10 0.22
8 10 0.3
我想通过资产组为此表添加一个公共值。
Loan_Num asset LTV cV
1 20 0.2 0.2
2 20 0.2 0.2
3 20 0.12 0.2
4 20 0.2 0.2
5 10 0.3 0.3
6 10 0.3 0.3
7 10 0.22 0.3
8 10 0.3 0.3
有任何建议如何做到这一点?是否存在共同价值的内置函数?
答案 0 :(得分:1)
这样做的一种方法是
WITH CTE1
AS (SELECT *,
COUNT(*) OVER (PARTITION BY [asset], [LTV]) AS C
FROM YourTable),
CTE2
AS (SELECT *,
RANK() OVER (PARTITION BY [asset] ORDER BY C DESC, [LTV] DESC) AS R
FROM CTE1)
SELECT [Loan_Num],
[asset],
[LTV],
MAX(CASE
WHEN R = 1
THEN [LTV]
END) OVER (PARTITION BY [asset]) AS cV
FROM CTE2
虽然实际上这会更有效,因为它会删除排序
WITH CTE1
AS (SELECT *,
COUNT(*) OVER (PARTITION BY [asset], [LTV]) AS C
FROM YourTable),
CTE2
AS (SELECT *,
MAX(C) OVER (PARTITION BY [asset]) AS MaxC
FROM CTE1)
SELECT [Loan_Num],
[asset],
[LTV],
MAX(CASE
WHEN C = MaxC
THEN [LTV]
END) OVER (PARTITION BY [asset]) AS cV
FROM CTE2