我有一个“Principal”表,可以有多个EmployeeId。对于每个员工ID,都有一个所有权百分比。此表还维护每个所有权百分比的主体名称。例如
EmpId OwnershipPercent Name
------- ----------------- ---------
100 50 John
100 30 Neil
100 20 Mark
现在,我需要为每位员工获取其名称最高和第二高的所有权%。为此,我使用以下查询来获得所有权%: -
SELECT
EmpId, CAST(isNULL([First], 0) AS DECIMAL (12,2)) [First OwnershipPercent],
CAST(isNULL([Second],0) AS DECIMAL (12,2)) [Second OwnershipPercent]
FROM
(
SELECT EmpId, OwnershipPercent, CASE WHEN SNo = 1 THEN 'First' ELSE 'Second' END [Priority]
FROM
(
SELECT ROW_NUMBER() over(partition by MerchantId order by MerchantId, OwnershipPercent desc) [SNo], *
FROM ( SELECT DISTINCT EmpId, OwnershipPercent FROM Principal) t
) t1
WHERE t1.SNo <=2
) t2
PIVOT
(
Avg(OwnershipPercent) FOR Priority IN ([First],[Second])
)AS pvt
我无法使用此查询获取每个%的名称。请帮忙
答案 0 :(得分:2)
您可以执行GROUP BY
并使用CASE WHEN
。这样的事情。
;WITH CTE AS
(
SELECT EmpId, Name,OwnershipPercent,ROW_NUMBER()OVER(PARTITION BY EmpId ORDER BY OwnershipPercent DESC) rn
FROM Principal
)
SELECT EmpID,
MAX(CASE WHEN rn = 1 THEN Name END) Highest,
MAX(CASE WHEN rn = 1 THEN OwnershipPercent END) Highest_perc,
MAX(CASE WHEN rn = 2 THEN Name END) SecondHighest,
MAX(CASE WHEN rn = 2 THEN OwnershipPercent END) SecondHighest_perc
FROM CTE
WHERE rn IN (1,2)
GROUP BY EmpID
答案 1 :(得分:0)
SQL Server 2012支持其他窗口聚合函数,在这种情况下,您需要LEAD:
SELECT *
FROM
(
SELECT
MerchantId,
OwnershipPercent, -- current row
LEAD(OwnershipPercent) -- next row
over(partition by MerchantId
order by OwnershipPercent desc) AS nextPercent,
LEAD(Name) -- next row
over(partition by MerchantId
order by OwnershipPercent desc) AS nextName,
ROW_NUMBER(OwnershipPercent)
over(partition by MerchantId
order by OwnershipPercent desc) AS SNo
FROM Principal
-- GROUP BY works the same as DISTINCT
GROUP BY MerchantId, OwnershipPercent
) t
WHERE SNo = 1