答案 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 ALL
或UNION
(如果您要删除重复项)并为查询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
操作将抛出错误