I have looked at many examples of selecting many columns but only grouping by 1 column and mine seem to give me duplicate results. See below I would like to select all the columns in my table but would like to only GROUP BY VehicleId. On the screenshot you'll see that the results are actually not grouped by VehicleId.
Any idea on what I am doing wrong?
Try 1:
SELECT
h.*,
TotalFines = 1,
TotalIncidents = 1,
TotalVehicleAllocations = 1,
TotalVehicleConditions = 1,
TotalMileageApplications = 1
FROM
(
SELECT h1.VehicleId FROM [dbo].[VehicleHistory] h1 GROUP BY h1.VehicleId
) GroupedList
INNER JOIN [dbo].[VehicleHistory] h ON GroupedList.VehicleId=h.VehicleId
ORDER BY
h.VehicleId;
Try 2:
SELECT t1.* FROM VehicleHistory t1
INNER JOIN
(
SELECT VehicleId FROM VehicleHistory GROUP BY VehicleId
) t2
ON t1.VehicleId=t2.VehicleId
Both queries produce the same results with duplicate rows for each VehicleId as per below:
Here's my expected results below. The results are a query produced by Entity Framework. But I would like to rewrite the linq query into T-SQL:

