我有这个查询
SELECT
MAX([ID]),
[sr].[EmpId],
[vw].[EmpName],
[sr].[IAmount]
FROM
[SRev] [sr]
INNER JOIN
[vwemp] [vw] ON [sr].[EmpId] = [vw].[EmpId]
INNER JOIN
[SalaryType] [st] ON [st].[SalaryType] = [sr].[SalaryType]
WHERE
[sr].[EmpId] IN (125553)
GROUP BY
[sr].[EmpId], [vw].[EmpName], [sr].[IAmount];
此查询返回如下结果集:
(No column name) EmpId EmpName IAmount
-----------------------------------------------
1687106 12553 BABC -8500
2136112 12553 BABC 936
1782854 12553 BABC 1225
1687106 12553 BABC 3000
2628907 12553 BABC 22839
我只想针对每个empid
进行最大记录(No column name) EmpId EmpName IAmount
-----------------------------------------------
2628907 12553 BABC 22839
答案 0 :(得分:1)
听起来你想要使用ROW_NUMBER
和CTE:
WITH CTE AS(
SELECT ID, --not sure of the lias for this one
sr.EmpID,
vw.EmpName,
sr.IAmount,
ROW_NUMBER() OVER (PARTITION BY sr.EmpId ORDER BY ID DESC) AS RN
FROM SRev sr
INNER JOIN vwemp vw ON sr.EmpId = vw.EmpId
INNER JOIN SalaryType st ON st.SalaryType = sr.SalaryType
WHERE sr.EmpId = 125553)
SELECT ID,
EmpId,
EmpName,
IAmount
FROM CTE
WHERE RN = 1;
请注意,这是未经测试的,因为我没有任何耗材样本数据或DDL(查询中的结果集)。