合并两个SQL选择的结果

时间:2016-09-27 11:29:32

标签: sql sql-server select

我有以下两个SQL选择:

versionCode

他们返回以下结果如下:

Returned result

如何通过在第一个结果集上添加两列(欠款和游戏玩法)来将结果组合在一起?

2 个答案:

答案 0 :(得分:3)

这是一个通用的解决方案:

SELECT T1.*, T2.owed, T2.gamesplayed FROM
(
  select u.ID,name, "Desc", sum(pp.amount) as paid
  from [dbo].[Users] u,[dbo].[UserTypes] ut, [dbo].[PlayerPayments] pp
  where u.UserTypeID = ut.ID and u.ID = pp.UserID
  group by u.ID,Name,"Desc"
) T1
JOIN
(
  select u.ID,name, "Desc", sum(ga.GamePrice) as owed, count(ga.ID) as gamesplayed
  from [dbo].[Users] u,[dbo].[UserTypes] ut, [dbo].[Games] ga, [dbo].[GamePlayers] gp
  where u.UserTypeID = ut.ID and u.ID = gp.UserID and gp.GameID = ga.ID
  group by u.ID,Name,"Desc"
) T2
ON T1.ID=T2.ID

答案 1 :(得分:1)

您必须使用UNION ALLUNION(如果您要删除重复项)并为查询1中的额外列传递默认值

select u.ID,name, "Desc", sum(pp.amount) as paid, 0 as owed, 0 as gamesplayed
from [dbo].[Users] u,[dbo].[UserTypes] ut, [dbo].[PlayerPayments] pp
where u.UserTypeID = ut.ID and u.ID = pp.UserID
group by u.ID,Name,"Desc";
UNION ALL
select u.ID,name, "Desc", sum(ga.GamePrice) as owed, count(ga.ID) as gamesplayed
from [dbo].[Users] u,[dbo].[UserTypes] ut, [dbo].[Games] ga, [dbo].[GamePlayers] gp
where u.UserTypeID = ut.ID and u.ID = gp.UserID and gp.GameID = ga.ID
group by u.ID,Name,"Desc";

注意此外,查询1中添加的额外列的数据类型必须与查询2中的列匹配,否则UNION操作将抛出错误