积极答复者
请问一个主附表自己之间的统计SQL该如何写?

问题
答案
-
思路:
对b求和后左连接到a表。
测试sql:
declare @a table (id int,name varchar(20)) declare @b table (id int,num int) insert into @a select 1,'a' union all select 2,'b' insert into @b select 1,10 union all select 1,20 select a.id,a.name,isnull(b.sumnum ,0) as sumnum from @a a left join ( select id,SUM(num) as sumnum from @b group by id ) b on a.id=b.id
id name sumnum
----------- -------------------- -----------
1 a 30
2 b 0
family as water- 已建议为答案 Ai-hua Qiu 2011年3月1日 6:48
- 已标记为答案 Ai-hua Qiu 2011年3月8日 6:54
-
你好,
除了上面的方法外,如果你使用SQL Server 2005 或者以上版本,我们可以使用公共表表达式,请参阅下面的语句:
;WITH CTE(id,name,num) AS ( SELECT A.id,A.name,B.num FROM @a A LEFT JOIN @b B ON A.id=B.id ) SELECT id,name,ISNULL(SUM(num),0) AS SumNum FROM CTE GROUP BY id,name
更多信息,请参阅:
使用公用表表达式
http://msdn.microsoft.com/zh-cn/library/ms190766.aspx谢谢,
邱爱华
Ai-hua Qiu[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 Ai-hua Qiu 2011年3月8日 6:54
全部回复
-
思路:
对b求和后左连接到a表。
测试sql:
declare @a table (id int,name varchar(20)) declare @b table (id int,num int) insert into @a select 1,'a' union all select 2,'b' insert into @b select 1,10 union all select 1,20 select a.id,a.name,isnull(b.sumnum ,0) as sumnum from @a a left join ( select id,SUM(num) as sumnum from @b group by id ) b on a.id=b.id
id name sumnum
----------- -------------------- -----------
1 a 30
2 b 0
family as water- 已建议为答案 Ai-hua Qiu 2011年3月1日 6:48
- 已标记为答案 Ai-hua Qiu 2011年3月8日 6:54
-
你好,
除了上面的方法外,如果你使用SQL Server 2005 或者以上版本,我们可以使用公共表表达式,请参阅下面的语句:
;WITH CTE(id,name,num) AS ( SELECT A.id,A.name,B.num FROM @a A LEFT JOIN @b B ON A.id=B.id ) SELECT id,name,ISNULL(SUM(num),0) AS SumNum FROM CTE GROUP BY id,name
更多信息,请参阅:
使用公用表表达式
http://msdn.microsoft.com/zh-cn/library/ms190766.aspx谢谢,
邱爱华
Ai-hua Qiu[MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 Ai-hua Qiu 2011年3月8日 6:54