Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 3 tables

1 for Vehicles
SQL
VehicleId
Code


1 for Oweners
SQL
OwnerId
Name

1 for Vehicle Owner History
SQL
VehicleId
OwenerId
OwnedFromDate

What I need to do is get a list of every vehicle and who owned the vehicle on a date specifed by the user e.g. TOP 1 for each vehicle WHERE OwnedFromDate <=
Specified Date ORDER BY OwnedFromDate DESCending.

SQL
SELECT  TOP 1  dbo.Owners.HaulierId, dbo.Vehicles.VehicleId, dbo.Vehicles.Code, dbo.Owners.Name, dbo.VehicleOwnershipHistory.OwnedFromDate
FROM         dbo.VehicleOwnershipHistory INNER JOIN
                      dbo.Vehicles ON dbo.VehicleOwnershipHistory.VehicleId = dbo.Vehicles.VehicleId INNER JOIN
                      dbo.Haulier ON dbo.VehicleOwnershipHistory.OwnerId = dbo.Owner.HaulierId
WHERE dbo.VehicleOwnershipHistory.OwnedFromDate <= @Date
ORDER BY dbo.VehicleOwnershipHistory.OwnedFromDate DESC
Posted
Comments
kiran dangar 19-Oct-11 2:01am    
I guess the problem is multiple records for the same Date...

1 solution

Hi, RANK() might be useful in this scenario.

Please try below query..

SQL
SELECT
    dbo.Owners.HaulierId,
    dbo.Vehicles.VehicleId,
    dbo.Vehicles.Code,
    dbo.Owners.Name,
    dbo.VehicleOwnershipHistory.OwnedFromDate,
    RANK() over(partition by dbo.VehicleOwnershipHistory.OwnedFromDate order by dbo.Owners.HaulierId) Rnk
FROM dbo.VehicleOwnershipHistory
    INNER JOIN dbo.Vehicles
        ON dbo.VehicleOwnershipHistory.VehicleId = dbo.Vehicles.VehicleId
    INNER JOIN dbo.Haulier
        ON dbo.VehicleOwnershipHistory.OwnerId = dbo.Owner.HaulierId

WHERE dbo.VehicleOwnershipHistory.OwnedFromDate <= @Date
    and Rnk = 1
ORDER BY dbo.VehicleOwnershipHistory.OwnedFromDate DESC


From your query i have removed top 1 and used
SQL
RANK() over(partition by dbo.VehicleOwnershipHistory.OwnedFromDate order by dbo.Owners.HaulierId) Rnk


and put a condition to fetch the data with only First Rank
SQL
Where Rnk = 1


Hope this will help..
 
Share this answer
 
v2
Comments
Steven J Jowett 19-Oct-11 5:17am    
Thanks for help, pointed me in the right direction. T-SQL not the strongest string in my bow and the Rank function is a new one for me. By the way, SQL does not like filtering the the Rnk column, but I've worked around that. Thanks again.
kiran dangar 19-Oct-11 5:41am    
yes Rnk wont be available directly in Where clause.. need to put one more select statement..
You can also use Row_number() & DENSE_RANK() are also very useful... you can have a look at those also.
JQuery Geeks 24-Oct-11 1:36am    
good one kiran

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900