0

我是来自以下查询的 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
4

3 回答 3

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
于 2013-05-31T08:33:45.793 回答
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
于 2013-05-31T08:40:34.723 回答
0

你不能只在UNION这里使用 a;考虑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 有另一种选择。

于 2013-05-31T08:39:11.043 回答