日期:2014-05-19  浏览次数:20473 次

求查询,分不够再给
表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

(所影响