34,594
社区成员
发帖
与我相关
我的任务
分享
select
a.id,a.name,a.bankaccount,sum(b.amount) amount
from
a left join b
on
a.id=b.id
select A.id, A.name, A.bankaccount, sum(B.amount) as amount
from A, B
where A.id = B.id
group by A.id, A.name, A.bankaccount
if object_id('a') is not null drop table a
go
create table a(id int,name varchar(3),bankaccount int)
insert a
select 100,'aaa',123000 union all
select 200,'bbb',321000
if object_id('b') is not null drop table b
go
create table b(id int,amount int)
insert b
select 100,200 union all
select 100,310 union all
select 200,450 union all
select 200,540 union all
select 200,600
select a.id,bankaccount,sum(amount) amount
from a,b
where a.id=b.id
group by a.id,bankaccount
--结果
id bankaccount amount
100 123000 510
200 321000 1590
--> 生成测试数据表: [A]
IF OBJECT_ID('[A]') IS NOT NULL
DROP TABLE [A]
GO
CREATE TABLE [A] ([id] [int],[name] [nvarchar](10),[bankaccount] [int])
INSERT INTO [A]
SELECT '100','aaa','123000' UNION ALL
SELECT '200','bbb','321000'
--> 生成测试数据表: [B]
IF OBJECT_ID('[B]') IS NOT NULL
DROP TABLE [B]
GO
CREATE TABLE [B] ([id] [int],[amount] [int])
INSERT INTO [B]
SELECT '100','200' UNION ALL
SELECT '100','310' UNION ALL
SELECT '200','450' UNION ALL
SELECT '200','540' UNION ALL
SELECT '200','600'
--SELECT * FROM [A]
--SELECT * FROM [B]
-->SQL查询如下:
SELECT *
FROM a
CROSS APPLY(
SELECT SUM(amount)amount
FROM b
WHERE a.id=b.id
) c
/*
id name bankaccount amount
----------- ---------- ----------- -----------
100 aaa 123000 510
200 bbb 321000 1590
(2 行受影响)
*/
2005select a.id,a.name,a.bankaccount, t.amount from a join (
select id,sum(amount) amount from b group by id)t on t.id=a.id
select a.*,c.amount
from a, (selecvt id,sum(amount) as amount from b group by id) c
where a.id=c.id
select a.*,c.amount
from a, (selecvt id,sum(amount) as amount from b group by id) c
where a.id=c.id
select a.*,c.amount
from a, (selecvt id,sum(amount) as amount from b group by id) c
where a.id=c.id
select a.* , sum(b.amount) amount from a , b where a.id = b.id group by a.id , a.name , a.bankaccount
select a.* , (select sum(b.amount) from b where b.id = a.id) amount from a
select a.*,t.amount from a left join (select b.ID,amount=sum(b.amount) from b group by b.ID) t on a.ID=b.id
---测试数据---
if object_id('[A]') is not null drop table [A]
go
create table [A]([id] int,[name] varchar(3),[bankaccount] int)
insert [A]
select 100,'aaa',123000 union all
select 200,'bbb',321000
if object_id('[B]') is not null drop table [B]
go
create table [B]([id] int,[amount] int)
insert [B]
select 100,200 union all
select 100,310 union all
select 200,450 union all
select 200,540 union all
select 200,600
---查询---
select a.id,a.name,a.bankaccount,sum(b.amount) as amount
from a,b
where a.id=b.id
group by a.id,a.name,a.bankaccount
---结果---
id name bankaccount amount
----------- ---- ----------- -----------
100 aaa 123000 510
200 bbb 321000 1590
(2 行受影响)
select
a.id,a.name,a.bankaccount,sum(b.amount) amount
from 表A a left join 表B b on a.id=b.id group by a.id