2016-09-27 101 views
0

我有以下两个SQL选择:两个SQL的结果相结合,选择

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"; 

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"; 

以及返回下面的结果看起来像如下:

Returned result

我怎么能合并结果一起通过在第一个结果集中添加两列(欠款和游戏玩法)?

+1

[不良习惯踢:使用旧式JOIN](http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to-kick-using-old-style- joins.aspx) - 在ANSI - ** 92 ** SQL标准中**旧式*逗号分隔的表*样式列表已替换为* proper * ANSI'JOIN'语法(**超过20年**之前),并且不鼓励使用它 –

+1

哪种RDBMS适用于?请添加一个标签来指定您是使用'mysql','postgresql','sql-server','oracle'还是'db2' - 或者其他的东西。 –

回答

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 
+0

这工作。如果我想从同一个查询中得到“已付款”和“欠款”的区别,那有可能吗? – mpora

+1

您可以将列添加为表达式:'T1.paid-T2.owed' –

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操作将抛出错误

+0

该死!你很快haha – mfredy

+0

由于OP在讨论'向第一个结果集添加列',我认为他实际上是在寻找一个JOIN(虽然我以为他也是第一个在讨论它)。 – Jens