34,594
社区成员
发帖
与我相关
我的任务
分享
declare @tb table(客户 char(1),供应商 char(1),借入 int,借出 int)
insert into @tb select 'A', '', 8,0
insert into @tb select '' , 'A',0,2
insert into @tb select '' , 'A',0,1
insert into @tb select 'B', '' ,3,0
insert into @tb select '' , 'C',0,4
select
[供应商]= case when isnull(供应商,'')>'' then 供应商 else 客户 end,
sum(借入-借出) as 金额
from
@tb
group by case when isnull(供应商,'')>'' then 供应商 else 客户 end
/*
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
供应商 金额
---- -----------
A 5
B 3
C -4
(所影响的行数为 3 行)
*/
你的表很有问题吧?
create table tb (客户 char(1),供应商 char(1),借入 int,借出 int)
insert into tb select 'A', 8 ,0
insert into tb select 'A', 0 ,2
insert into tb select 'A', 0 ,1
insert into tb select 'B', 3 ,0
insert into tb select 'C', 0 ,4
select * from tb
服务器: 消息 213,级别 16,状态 4,行 1
插入错误: 列名或所提供值的数目与表定义不匹配。
服务器: 消息 213,级别 16,状态 1,行 1
插入错误: 列名或所提供值的数目与表定义不匹配。
服务器: 消息 213,级别 16,状态 1,行 1
插入错误: 列名或所提供值的数目与表定义不匹配。
服务器: 消息 213,级别 16,状态 1,行 1
插入错误: 列名或所提供值的数目与表定义不匹配。
服务器: 消息 213,级别 16,状态 1,行 1
插入错误: 列名或所提供值的数目与表定义不匹配。
create table tb1(客商 varchar(10))
insert into tb1 values('A')
insert into tb1 values('B')
insert into tb1 values('C')
create table tb2(客户 char(1),供应商 char(1),借入 int,借出 int)
insert into tb2 select 'A', '', 8,0
insert into tb2 select '' , 'A',0,2
insert into tb2 select '' , 'A',0,1
insert into tb2 select 'B', '' ,3,0
insert into tb2 select '' , 'C',0,4
go
select m.客商 供应商 , sum(isnull(n.借入,0) - isnull(n.借出,0)) 余额 from tb1 m,
(
select 客户,借入,借出 from tb2 where 供应商 = ''
union all
select 供应商,借入,借出 from tb2 where 客户 = ''
) n
where m.客商 = n.客户
group by m.客商
order by m.客商
drop table tb1,tb2
/*
供应商 余额
---------- -----------
A 5
B 3
C -4
(所影响的行数为 3 行)
*/
create table tb(客户 char(1),供应商 char(1),借入 int,借出 int)
insert into tb select 'A','A',8,0
insert into tb select 'A','A',0,2
insert into tb select 'A','A',0,1
insert into tb select 'B','B',3,0
insert into tb select 'B','C',0,4
select 供应商,isnull(sum(借入),0)-isnull(sum(借出),0) 余额
from tb
group by 供应商
drop table tb
/*
供应商 余额
---- -----------
A 5
B 3
C -4
(所影响的行数为 3 行)
*/