A表                               B表
用户编码 用户名 示数  建立日期     用户编码 本月示数 日期
1          a     0     2006-2-2      1           3     2006-3-1
2          b     5     2006-3-5      1           5     2006-4-1
3          c     3     2006-3-4      1           9     2006-5-1
4          d     4     2006-4-12     2           9     2006-4-1
                                    2           13    2006-5-1
                                    3            8    2006-4-1
                                    3            15   2006-5-1对于这种表 如何查询得到如下结果 即B表有示数取B表最新示数,B表没有取A表建立时示数
1  a   9
2  b   13
3  c   15 
4  d   4如果用双重循环来做 A表记录越多速度越慢 超过3000条时就感觉到慢 现在有5000多条了
如何用一条sql来实现这种查询?

解决方案 »

  1.   

    一个查询:
    select a.用户编码,a.用户名,
    isnull(b.本月示数,a.示数) as 示数
    from a left join b b1
    on a.用户编码=b1.用户编码
    and b1.日期=(select max(日期) from b where 用户编码=b1.用户编码)
      

  2.   

    declare @A table(
    用户编码 int,
    用户名 varchar(20),
    示数 int,
    建立日期 datetime
    )declare @B table(
    用户编码 int,
    本月示数 int,
    日期 datetime
    )insert @a
    select 
    1,          'a',     0,     '2006-2-2'
    union all select
    2,          'b',     5,     '2006-3-5'
    union all select
    3,          'c',     3,     '2006-3-4'
    union all select
    4,          'd',     4,     '2006-4-12'insert @b
    select 
    1,           3,     '2006-3-1'
    union all select
    1,           5 ,    '2006-4-1'
    union all select
    1,           9  ,   '2006-5-1'
    union all select
    2,           9   ,  '2006-4-1'
    union all select
    2,           13   , '2006-5-1'
    union all select
    3,            8    ,'2006-4-1'
    union all select
    3,            15   ,'2006-5-1'select a.用户编码,a.用户名,
    isnull(b.本月示数,a.示数) as 示数
    from @a a left join @b b
    on a.用户编码=b.用户编码
    and b.日期=(select max(日期) from @b where 用户编码=b.用户编码)--结果
    用户编码        用户名                  示数          
    ----------- -------------------- ----------- 
    1           a                    9
    2           b                    13
    3           c                    15
    4           d                    4(所影响的行数为 4 行)
      

  3.   

    access下用不起来 不支持连接查询