首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

求查询,分不够再给,该怎么处理

2012-04-08 
求查询,分不够再给表item列serialnoclerkcode10011100111002210031表payserialnoamountpayflag10011001001

求查询,分不够再给
表item
列serialno     clerkcode
      1001             1
      1001             1
      1002             2
      1003             1
表pay  
    serialno       amount     payflag
      1001               10             0
      1001               15             1
      1002               20             0
      1002               10             1
      1003               15             2
要求查询结果为
    clerkcode       amount     payflag
          1               10             0
          1               15             1
          2               20             0
          2               10             1
          1003         15             2
也就是结果中amount     payflag还是pay中的值(完全照搬pay的这2个字段.行数不能多),其实就是查询结果多一个clerkcode字段。这个字段用item的代替在item表里面serialno   和   clerkcode是一一对应的。

[解决办法]
if object_id( 'pubs..item ') is not null
drop table item
go

create table item(serialno varchar(10),clerkcode varchar(10))
insert into item(serialno,clerkcode) values( '1001 ', '1 ')
insert into item(serialno,clerkcode) values( '1001 ', '1 ')
insert into item(serialno,clerkcode) values( '1002 ', '2 ')
insert into item(serialno,clerkcode) values( '1003 ', '1 ')
go

if object_id( 'pubs..pay ') is not null
drop table pay
go

create table pay(serialno varchar(10),amount int,payflag int)
insert into pay(serialno,amount,payflag) values( '1001 ', 10, 0)
insert into pay(serialno,amount,payflag) values( '1001 ', 15, 1)
insert into pay(serialno,amount,payflag) values( '1002 ', 20, 0)
insert into pay(serialno,amount,payflag) values( '1002 ', 10, 1)
insert into pay(serialno,amount,payflag) values( '1003 ', 15, 2)
go

select t.clerkcode as serialno,pay.amount,pay.payflag from pay,
(
select distinct * from item
)
t
where t.serialno = pay.serialno

drop table pay
drop table item

/*
serialno amount payflag
---------- ----------- -----------
1 10 0
1 15 1
2 20 0
2 10 1
1 15 2

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

热点排行