表A:
商品ID,商品名称,商品类型
1001    名称1   类型1
1002    名称2   类型2
1003    名称3   类型3
1004    名称4   类型4
……表B
商品ID,价格,设定时间,    设定人
1001   100   2012-12-01  用户1
1001   200   2012-12-02  用户1
1001   300   2012-12-03  用户2
1001   100   2012-12-04  用户3
1002    49   2012-12-01  用户1
1002    50   2012-12-11  用户1
1002    55   2012-12-09  用户2要求得到如下的表
商品ID,商品名称,类型,高价,高价时间,  高价设定人,低价,低价时间,    低价设定人
1001    名称1  类型1  300 2012-12-03  用户2     100  2012-12-01   用户1
1002    名称2  类型2  55  2012-12-09  用户2     49   2012-12-01   用户1
1003    名称3  类型3  0                          0
1004    名称4  类型4  0                          0就是把两个表合起来。

解决方案 »

  1.   

    create table t1(ID int,商品名称 nvarchar(10),商品类型 nvarchar(10))
    insert into  t1 select 1001,'名称1','类型1'
    insert into  t1 select 1002,'名称2','类型2'
    insert into  t1 select 1003,'名称3','类型3'
    insert into  t1 select 1004,'名称4','类型4'
    create table t2(ID int,价格 int,设定时间 datetime,设定人 nvarchar(10))
    insert into  t2 select 1001,100,'2012-12-01','用户1'
    insert into  t2 select 1001,200,'2012-12-02','用户1'
    insert into  t2 select 1001,300,'2012-12-03','用户2'
    insert into  t2 select 1001,100,'2012-12-04','用户3'
    insert into  t2 select 1002,49,'2012-12-01','用户1'
    insert into  t2 select 1002,50,'2012-12-11','用户1'
    insert into  t2 select 1002,55,'2012-12-09','用户2'
    go
    select a.id,a.商品名称,a.商品类型,b.价格 as 高价,b.设定时间 as 高价时间,b.设定人 as 高价设定人,c.价格 as 低价,c.设定时间 as 低价时间,c.设定人 as 低价设定人
    from t1 a left join t2 b on a.id=b.id
    left join t2 c on a.id=c.id
    where not exists(select 1 from t2 where id=b.id and 价格>b.价格)
    and not exists(select 1 from t2 where id=c.id and 价格<c.价格)
    /*
    id          商品名称       商品类型       高价          高价时间                    高价设定人      低价          低价时间                    低价设定人
    ----------- ---------- ---------- ----------- ----------------------- ---------- ----------- ----------------------- ----------
    1001        名称1        类型1        300         2012-12-03 00:00:00.000 用户2        100         2012-12-01 00:00:00.000 用户1
    1001        名称1        类型1        300         2012-12-03 00:00:00.000 用户2        100         2012-12-04 00:00:00.000 用户3
    1002        名称2        类型2        55          2012-12-09 00:00:00.000 用户2        49          2012-12-01 00:00:00.000 用户1
    1003        名称3        类型3        NULL        NULL                    NULL       NULL        NULL                    NULL
    1004        名称4        类型4        NULL        NULL                    NULL       NULL        NULL                    NULL(5 行受影响)
    */
    go
    drop table t1,t2