SQL Server +'合并结果'

时间:2013-05-31 08:29:30

标签: sql sql-server

我是以下查询中的2个结果集,我想将结果“合并”到1个单独的表中,但不知道如何从这里开始,有人可以请提供一些指导:

SELECT userid, vehicleId, count(vehicleId) As SearchCount FROM MemberSearches 
GROUP BY userid, vehicleId 
ORDER BY count(vehicleId) DESC

SELECT f.UserId, v.AutoId AS VehicleId, count(v.AutoId) AS SearchCount FROM Favorites f
LEFT JOIN [SellPost] sp
ON (f.PostId = sp.AutoId)
LEFT JOIN [Vehicle] v
ON (sp.CarId = v.AutoId)
GROUP BY f.UserId, v.AutoId
ORDER BY COUNT(v.AutoId) DESC

第一次选择的结果:

UserId       VehicleId  SearchCount
2926FC8A78FB    7       3
2926FC8A78FB    2       2
2926FC8A78FB    6       1

第二次选择的结果:

UserId       VehicleId  SearchCount
2926FC8A78FB    1       5
2926FC8A78FB    2       5

我需要达到最终结果:

UserId       VehicleId  SearchCount
2926FC8A78FB    1       5
2926FC8A78FB    2       7
2926FC8A78FB    6       1
2926FC8A78FB    7       3

3 个答案:

答案 0 :(得分:2)

效率不高,只是测试它的工作......

   SELECT userid, vehicleId, SUM(SearchCount) As SearchCount
FROM
(SELECT userid, vehicleId, count(vehicleId) As SearchCount FROM MemberSearches 
GROUP BY userid, vehicleId 
UNION ALL
SELECT f.UserId, v.AutoId AS VehicleId, count(v.AutoId) AS SearchCount FROM Favorites f
LEFT JOIN [SellPost] sp
ON (f.PostId = sp.AutoId)
LEFT JOIN [Vehicle] v
ON (sp.CarId = v.AutoId)
GROUP BY f.UserId, v.AutoId
) t
GROUP BY userid, vehicleId

答案 1 :(得分:1)

SELECT
    userid, vehicleId, count(*) As SearchCount
FROM (
    SELECT userid, vehicleId FROM MemberSearches 

    UNION ALL

    SELECT f.UserId, v.AutoId FROM Favorites f
    LEFT JOIN [SellPost] sp
    ON (f.PostId = sp.AutoId)
    LEFT JOIN [Vehicle] v
    ON (sp.CarId = v.AutoId)
) AS X
GROUP BY userid, vehicleId 
ORDER BY 3 DESC

答案 2 :(得分:0)

你不能在这里使用UNION;考虑 vehicleid 2 ,其中所需的结果是每个子查询中的行总数。

您可以将两个结果合并在一起:

SELECT t1.userid, t2.vehicleId, SearchCount = t1.SearchCount + t2.SearchCount
FROM 
(
  SELECT userid, vehicleId, count(vehicleId) As SearchCount FROM MemberSearches 
  GROUP BY userid, vehicleId
) t1
INNER JOIN
(
  SELECT f.UserId, v.AutoId AS VehicleId, count(v.AutoId) AS SearchCount FROM Favorites f
  LEFT JOIN [SellPost] sp
  ON (f.PostId = sp.AutoId)
  LEFT JOIN [Vehicle] v
  ON (sp.CarId = v.AutoId)
  GROUP BY f.UserId, v.AutoId
) t2 on t1.userid = t2.userid and t1.vehicleid = t2.vehicleid
ORDER BY userid, vehicleid

根据数据的不同,您可能需要在此处使用LEFTFULL加入。

或者用户@Serge还有另一种选择。