select * from kc
select * from score结果:
id       mc
------------------
hx 化学
sx 数学
wl 物理
yw 语文id      xm              kc       fs    
-----------------------------------
1 张三         yw 45
2 李四         wl 88
3 李四         yw 88
5 李四         sx 89
6 李四         hx 91
7 王五         sx 64
8 王五         yw 61查询出 把没考的课程以0 分补全 
看上去每个人都有四条考试得分记录

解决方案 »

  1.   

    if not object_id('kc') is null
    drop table kc
    Go
    Create table kc([id] nvarchar(2),[mc] nvarchar(2))
    Insert kc
    select N'hx',N'化学' union all
    select N'sx',N'数学' union all
    select N'wl',N'物理' union all
    select N'yw',N'语文'
    Go
    if not object_id('score') is null
    drop table score
    Go
    Create table score([id] int,[xm] nvarchar(2),[kc] nvarchar(2),[fs] int)
    Insert score
    select 1,N'张三',N'yw',45 union all
    select 2,N'李四',N'wl',88 union all
    select 3,N'李四',N'yw',88 union all
    select 5,N'李四',N'sx',89 union all
    select 6,N'李四',N'hx',91 union all
    select 7,N'王五',N'sx',64 union all
    select 8,N'王五',N'yw',61
    go
    select a.xm,
           a.mc,
           isnull(b.[fs],0)[fs]
    from(
    select a.*,
           b.[xm]
    from kc a,(select distinct [xm] from [score])b)a
    left join [score] b
    on a.ID=b.[kc] and a.xm=b.xm
    /*
    xm   mc   fs
    ---- ---- -----------
    李四   化学   91
    李四   数学   89
    李四   物理   88
    李四   语文   88
    王五   化学   0
    王五   数学   64
    王五   物理   0
    王五   语文   61
    张三   化学   0
    张三   数学   0
    张三   物理   0
    张三   语文   45(12 行受影响)
    */