troubleshooting Question

SQL Select query having a table input for a condition

Avatar of sequel_prequel
sequel_prequel asked on
Microsoft SQL ServerMicrosoft SQL Server 2008SQL
9 Comments1 Solution324 ViewsLast Modified:

In SQL SERVER 2008 I have a table called [Trips].

Select [iVehicleID],SUM(fTripDistance) AS KM
  FROM Trips
  WHERE [iVehicleID]=5 
and [dtDateTime]>='2011-11-17 19:01:46.300'
  GROUP BY [iVehicleID]
iVehicleID      KM
5                    9972

I have another table called [Conditions] where the vehicleID only appears once:

SELECT [iVehicleID],[dtDateTime]
  FROM [Conditions]
iVehicleID      dtDateTime
2                      2012-03-15 17:52:17.020
3                      2012-03-16 00:08:52.077
4                      2012-03-15 20:03:59.020
5                      2011-11-17 19:01:46.300
6                      2012-03-15 19:09:44.020


Conceptually, I'd like to do the following:

Select [iVehicleID],SUM(fTripDistance) AS KM
  FROM Trips
WHERE [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
Chris Ashcraft
Senior Analyst - Technology

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 9 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 9 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros