Brock
asked on
Mssql - Sql Query Issue
Hi,
SELECT
CNT.EMPLID, CNT.ONTRACT_NUM,CNT.START_ DATE, CNT.END_DATE FROM
PS_CONTRACT CNT
INNER JOIN PS_CAATNTFY_TMP TMP ON CNT.EMPLID = TMP.EMPLID
AND CNT.START_DATE = TMP.START_DATE
-- This yields results like :
1000926 118329 2013-05-01 00:00:00.000 2013-08-30 00:00:00.000
1000926 118330 2013-05-01 00:00:00.000 2014-04-01 00:00:00.000
I want only the second row where the maximum end-date is 2014-04-01. Without having to do a second pass of the data in another query, how would I do this as part of the above query.
Any help would be greatly appreciated,
Nigluc
SELECT
CNT.EMPLID, CNT.ONTRACT_NUM,CNT.START_
PS_CONTRACT CNT
INNER JOIN PS_CAATNTFY_TMP TMP ON CNT.EMPLID = TMP.EMPLID
AND CNT.START_DATE = TMP.START_DATE
-- This yields results like :
1000926 118329 2013-05-01 00:00:00.000 2013-08-30 00:00:00.000
1000926 118330 2013-05-01 00:00:00.000 2014-04-01 00:00:00.000
I want only the second row where the maximum end-date is 2014-04-01. Without having to do a second pass of the data in another query, how would I do this as part of the above query.
Any help would be greatly appreciated,
Nigluc
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I'd recommend row_number() if it's available (as appari has done), alternatively I'd go with a joined subquery
SELECT
CNT.EMPLID
, CNT.ONTRACT_NUM
, CNT.START_DATE
, CNT.END_DATE
FROM PS_CONTRACT CNT
INNER JOIN (
SELECT
CNT.EMPLID AS EID, MAX(CNT.END_DATE) as MAX_END_DATE
FROM PS_CONTRACT
) AS MX ON CNT.EMPLID = mx.EID AND CNT.END_DATE = MX.MAX_END_DATE
INNER JOIN PS_CAATNTFY_TMP TMP ON CNT.EMPLID = TMP.EMPLID
AND CNT.START_DATE = TMP.START_DATE
;
the disadvantage of any solution based on MAX() is that you might (very rarely) have more than one record matching to that date, but a row_number() solution can only grant the number 1 once within a partition and may also use other fields in the order by as tiebreakers to overcome that should it ever be needed.
Alternatively you can use TOP 1:
SELECT TOP 1
CNT.EMPLID, CNT.ONTRACT_NUM,CNT.START_DATE, CNT.END_DATE FROM
PS_CONTRACT CNT
INNER JOIN PS_CAATNTFY_TMP TMP ON CNT.EMPLID = TMP.EMPLID
AND CNT.START_DATE = TMP.START_DATE
ORDER BY CNT.END_DATE DESC
:) yes that too, if only one record is the total required
ASKER
As I begin my work day, I was so happy to find a solution to my problem.
Thank you to all,
I really appreciate it,
Nigluc
Thank you to all,
I really appreciate it,
Nigluc
Try this:
Open in new window
What I've added is a condition demanding that the result rows have an END_DATE equal to the largest END_DATE in the result set.hth
Mike