有AB两表,怎样用SQL语句连接得到C表?C表中钢笔数量只出现1次,请高手赐教
A表:品名    日期          单价
     钢笔    2010-10-10    5
     钢笔    2010-10-11    5.5
     铅笔    2010-10-11    2B表:品名    数量
     钢笔    20
     铅笔    30 C表:品名    日期          单价   数量
     钢笔    2010-10-10    5      20
     钢笔    2010-10-11    5.5
     铅笔    2010-10-11    2      30

解决方案 »

  1.   


    if object_id('TA') is not null
       drop table TA
    go
    create table TA
    (
     品名 varchar(10),
     日期 varchar(10),
     单价 numeric(9,1)
    )
    go
    insert into TA
    select '钢笔','2010-10-10',5 union all
    select '钢笔','2010-10-11',5.5 union all
    select '铅笔','2010-10-11',2
    go
    if object_id('TB') is not null
       drop table TB
    go
    create table TB
    (
     品名 varchar(10),
     数量 int
    )
    go
    insert into TB
    select '钢笔',20 union all
    select '铅笔',30
    goSELECT a.品名,日期,单价,数量=CASE WHEN a.品名=(SELECT top 1 品名 FROM TA where 品名=a.品名) and 日期=(select min(日期) from ta where 品名=a.品名) then cast(数量 as varchar) else '' end from TA a left join TB b on a.品名=b.品名