Select [iVehicleID],SUM(fTripDistance) AS KM FROM TripsWHERE [iVehicleID]=(SELECT [iVehicleID] FROM [Conditions])and [dtDateTime]>=(SELECT [dtDateTime] FROM [Conditions]) GROUP BY [iVehicleID]
obviously, this is not allowed:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
but how can I make this work and such that one record is returned for each row in [Conditions]:
Final Expected results:
iVehicleID KM
2 8974
3 2654
4 8954
5 9972
6 8564
Thanks in advanced
Microsoft SQL ServerMicrosoft SQL Server 2008SQL
Last Comment
sequel_prequel
8/22/2022 - Mon
Chris Ashcraft
I believe this is what you want...
SELECT T.iVehicleID, SUM(T.fTripDistance) AS KMFROM [Trips] TINNER JOIN [Conditions] CON T.iVehicleID = C.iVehicleIDGROUP BY T.iVehicleID
For this example if I was to do things the long way:
Select * FROM(Select [iVehicleID],SUM(fTripDistance) AS KM FROM TripsWHERE [iVehicleID]=2and [dtDateTime]>='2012-03-15 17:52:17.020' GROUP BY [iVehicleID]) aUNION ALLSELECT * FROM(Select [iVehicleID],SUM(fTripDistance) AS KM FROM TripsWHERE [iVehicleID]=3and [dtDateTime]>='2012-03-16 00:08:52.077' GROUP BY [iVehicleID]) as b...
What I want is the total KMs traveled by each vehcile in the Conditions table but the KMs added should only be since the Trips.dtDateTime>=Conditons.dtDateTime.
but... I just tried something working off your suggestion and it seemed to work :)
SELECT T.iVehicleID, SUM(T.fTripDistance) AS KMFROM [Trips] TINNER JOIN [Conditions] CON T.iVehicleID = C.iVehicleIDAND T.dtDateTime>=C.dtDateTimeGROUP BY T.iVehicleID
ha - I thought I had changed my previous comment fast enough before you actually saw it. O well... I think i understand now what you are asking. My previous post should be what you need. I hope...
sequel_prequel
ASKER
Perfect. I like your's better as it returns all rows in Condition table where mine only returns the rows where the condition is satisfied. Thanks for your help.
Open in new window