我不知道如何用另一列选择具有最大列值组的行。我有T-SQL
CREATE PROC GET_USER
AS
BEGIN
SELECT A.USER_ID, B.START_DATE , D.START_DATE, A.FULL_NAME,A.COST_CENTER,
F.DEPARTMENT_NAME,G.BU_NAME
FROM USERS A INNER JOIN USER_PERSON B ON A.USER_ID=B.USER_ID
INNER JOIN TYPE_PERSON C ON C.TYPE_PERSON_ID = B.TYPE_PERSON_ID
INNER JOIN USER_TRANSACTION D ON D.USER_ID = A.USER_ID
INNER JOIN TRANSACTIONS E ON E.TRANSACTION_ID = D.TRANSACTION_ID
INNER JOIN DEPARTMENT F ON F.DEPARTMENT_ID = D.DEPARTMENT_ID
INNER JOIN BUS_UNIT G ON G.BU_ID = D.BU_ID
INNER JOIN BRANCH H ON H.BRANCH_ID = D.BRANCH_ID
INNER JOIN POSITION J ON J.POSITION_ID = D.POSITION_ID
WHERE A.FLAG = 'TRUE'
END
结果将选择max(B.START_DATE)和max(D.START_DATE)以及按USER_ID分组
答案 0 :(得分:1)
试试这个
SELECT T.USER_ID ,
MAX(T.START_DATE) AS [Max First Start Date] ,
MAX(T.[Second Start Date]) AS [Max Second Start Date]
FROM ( SELECT A.USER_ID ,
B.START_DATE ,
D.START_DATE AS [Second Start Date] ,
A.FULL_NAME ,
A.COST_CENTER ,
F.DEPARTMENT_NAME ,
G.BU_NAME
FROM USERS A
INNER JOIN USER_PERSON B ON A.USER_ID = B.USER_ID
INNER JOIN TYPE_PERSON C ON C.TYPE_PERSON_ID = B.TYPE_PERSON_ID
INNER JOIN USER_TRANSACTION D ON D.USER_ID = A.USER_ID
INNER JOIN TRANSACTIONS E ON E.TRANSACTION_ID = D.TRANSACTION_ID
INNER JOIN DEPARTMENT F ON F.DEPARTMENT_ID = D.DEPARTMENT_ID
INNER JOIN BUS_UNIT G ON G.BU_ID = D.BU_ID
INNER JOIN BRANCH H ON H.BRANCH_ID = D.BRANCH_ID
INNER JOIN POSITION J ON J.POSITION_ID = D.POSITION_ID
WHERE A.FLAG = 'TRUE'
) AS T
GROUP BY T.USER_ID