我用的是SQL Server 2000
表A中的数据如下:
DI      TM
D1      002
D2      023
D2      035

其中D001出现1次,D002出现2次
表B中的数据如下:
DI     KW
D1     a
D1     b
D1     c

D2     a
D2     d
D2     e

D3     b
D3     n

其中D1对应a、b、c,D2对应a、d、e,D3对应b,n
我想要统计的是,用表B中的KW和表A中的相应DI次数相乘,然后计算出KW的次数。
例如表A中的D1对应的a、b、c出现了1次,D2对应的a、d、e出现了2次,所以a出现了1+2=3次,b、c出现1次,d、e出现2次。D3对应的b、n因为没有在表A中出现,所以不用统计。
结果如下:
KW   Num
a    3
d    2
e    2
b    1
c    1

解决方案 »

  1.   

    MSSQL2005及以上版本:
    create table t1
    (
    di varchar(2),
    tm varchar(3)
    )
    insert into t1
    select 'D1', '002' union all
    select 'D2', '023' union all
    select 'D2', '035'
    create table t2
    (
    di varchar(2),
    kw varchar(1)
    )
    insert into t2
    select 'D1', 'a' union all
    select 'D1', 'b' union all
    select 'D1', 'c' union all
    select 'D2', 'a' union all
    select 'D2', 'd' union all
    select 'D2', 'e' union all
    select 'D3', 'b' union all
    select 'D3', 'n'
    select * from t1
    select * from t2;with aaa as
    (select kw,case when tm IS null then 0 else 1 end as acount from t2 left join t1 on t2.di=t1.di)
    select kw,SUM(acount) as num from aaa where acount>0 group by kw-------------------------
    kw num
    a 3
    b 1
    c 1
    d 2
    e 2如果是MSSQL2000,则使用子查询即可。