+ -
当前位置:首页 → 问答吧 → 求sql

求sql

时间:2011-12-23

来源:互联网

数据集1

名字 现金 银行
a 5 66
a 6 77
b 5 23

数据集2

名字 累计
a 599
b 444

要这样的结果
a 5 66 599
a 6 77
b 5 23 444
语句应该怎么写,谢谢!

作者: caoyang0299   发布时间: 2011-12-23

select * from a join b on a.名字=b.名字

作者: fredrickhu   发布时间: 2011-12-23

a 5 66 599
a 6 77 599
b 5 23 444
那样写的话是这样的结果,我就需要1个599

作者: caoyang0299   发布时间: 2011-12-23

SQL code

if object_id('tb1') is not null
   drop table tb1
go
create table tb1
(
 名字 varchar(10),
 现金 int,
 银行 int
)
go
insert into tb1
select 'a','5',66 union all
select 'a','6',77 union all
select 'b','5',23
go
if object_id('tb2') is not null
   drop table tb2
go
create table tb2
(
 名字 varchar(10),
 累计 int
)
go
insert into tb2
select 'a',599 union all
select 'b',444
go
select t1.名字,现金,银行,累计=isnull(ltrim(t2.累计),'') from
(
 select *,row=row_number() over(partition by 名字 order by getdate()) from tb1
)t1
left join 
(
 select *,row=row_number() over(partition by 名字 order by getdate()) from tb2
)t2 on t1.名字=t2.名字 and t1.row=t2.row
go
/*
名字         现金          银行          累计
---------- ----------- ----------- ------------
a          5           66          599
a          6           77          
b          5           23          444

(3 行受影响)
*/

作者: pengxuan   发布时间: 2011-12-23

SQL code
create table 数据集1
(
 名字 varchar(10),
 现金 int,
 银行 int
)
go
insert into 数据集1
select 'a','5',66 union all
select 'a','6',77 union all
select 'b','5',23
go
create table 数据集2
(
 名字 varchar(10),
 累计 int
)
go
insert into 数据集2
select 'a',599 union all
select 'b',444
go


select m.*,
       case when 现金 = (select top 1 现金 from 数据集1 where 名字 = m.名字) then cast(n.累计 as varchar) else '' end 累计
from  数据集1 m , 数据集2 n
where m.名字 = n.名字

drop table 数据集1,数据集2

/*
名字         现金          银行          累计                             
---------- ----------- ----------- ------------------------------ 
a          5           66          599
a          6           77          
b          5           23          444

(所影响的行数为 3 行)
*/

作者: dawugui   发布时间: 2011-12-23

谢谢,我试试

作者: caoyang0299   发布时间: 2011-12-23

+1
引用 4 楼 dawugui 的回复:
SQL code
create table 数据集1
(
名字 varchar(10),
现金 int,
银行 int
)
go
insert into 数据集1
select 'a','5',66 union all
select 'a','6',77 union all
select 'b','5',23
go
create table 数据集2
(
名字……

作者: szstephenzhou   发布时间: 2011-12-23

select a.名字,a.现金,a.银行,b.累计
from (select 名字,现金,银行 from 数据集1 )a
left join 
(select 名字,累计 from 数据集1) b
on a.名字=b.名字

这里的数据集1、2分别代表 你的数据表。

作者: qq517995084   发布时间: 2011-12-23