问题
Bit of an sql noob, have a list in table a of customercodes/phone numbers, and table b has all the call records.
I want to select the most recent call from table b for each of the customercodes/phone numbers in table a.
So far I have:
SELECT A.CustomerCode, A.PhoneNumber, B.StartTime
FROM tableA A INNER JOIN
tableB B ON ( A.PhoneNumber = B.PhoneNumber
AND A.CustomerCode = B.CustomerCode )
ORDER BY A.CustomerCode, A.CLI, B.StartTime DESC
But that is bringing up all the results from TableB. I literally just want to get the most recent call if that makes sense?
回答1:
You can join the calls table on itself, and specify that no later row may exist. Like:
SELECT A.CustomerCode, A.PhoneNumber, B.StartTime
FROM tableA A
INNER JOIN tableB B
ON A.PhoneNumber = B.PhoneNumber
AND A.CustomerCode = B.CustomerCode
LEFT JOIN tableB later
ON B.PhoneNumber = later.PhoneNumber
AND B.CustomerCode = later.CustomerCode
AND later.StartTime > B.StartTime
WHERE later.PhoneNumber is null
The condition later.PhoneNumber is null
says there can't be a later row. If there are multiple rows with the same StartTime, this will select all of them.
This allows you to select all columns from the latest call.
回答2:
If you only want the starttime from table b, you could use a group by
SELECT A.CustomerCode, A.PhoneNumber, max(B.StartTime)
FROM tableA A INNER JOIN
tableB B ON A.PhoneNumber = B.PhoneNumber
AND A.CustomerCode = B.CustomerCode
GROUP BY A.CustomerCode, A.PhoneNumber
ORDER BY A.CustomerCode, A.CLI
回答3:
Something like this?
SELECT A.CustomerCode, A.PhoneNumber, Max(B.StartTime) AS MaxOfStartTime
FROM A INNER JOIN B ON A.PhoneNumber = B.PhoneNumber
GROUP BY A.CustomerCode, A.PhoneNumber;
回答4:
SELECT A.CustomerCode, A.PhoneNumber, B.StartTime
FROM tableA A INNER JOIN tableB B
ON A.PhoneNumber = B.PhoneNumber AND A.CustomerCode = B.CustomerCode
WHERE B.StartTime = (SELECT MIN(StartTime) FROM B
WHERE PhoneNumber = A.PhoneNumber
AND CustomerCode = A.CustomerCode)
ORDER BY A.CustomerCode, A.CLI, B.StartTime DESC
I believe this will give your desired result, provided B.StartTime is unique in the set related to each row from table A. If you're dealing with a DateTime and events not too close together, this should be reliable.
The only other way I know is using CROSS APPLY in MSSQL 2005+
来源:https://stackoverflow.com/questions/1819003/sql-join-only-select-top-row-from-2nd-table