select XSName,XKName,ZYName,count(*)  as 数量
from (
select a.XSName,b.XKName,c.ZYName
from xs a,xk b,zy c,yw d
where d.xsid=a.xsid
and d.xkid=b.xkid
and d.zyid=c.zyid
union all
select a.XSName,b.XKName,c.ZYName
from xs a,xk b,zy c,sx d
where d.xsid=a.xsid
and d.xkid=b.xkid
and d.zyid=c.zyid
union all
select a.XSName,b.XKName,c.ZYName
from xs a,xk b,zy c,yy d
where d.xsid=a.xsid
and d.xkid=b.xkid
and d.zyid=c.zyid
union all
select a.XSName,b.XKName,c.ZYName
from xs a,xk b,zy c,其它科目表 d
where d.xsid=a.xsid
and d.xkid=b.xkid
and d.zyid=c.zyid
) as t

解决方案 »

  1.   

    正如一楼所说,设计上好像有点问题,各种资表如果有XKID字段,应该可以合并。
      

  2.   

    各种资源表都有 学科ID 和资源类别ID
      

  3.   

    正如一楼所说,设计上好像有点问题,各种资表如果有XKID字段,应该可以合并。
    ------------
    我要解解决的并不完全如此,只是简单的列出来
      

  4.   

    各种资源表都有 学科ID 和资源类别ID这个说得过去,但查询的时候,要从那些资源表中查找数据,这个要有个说明,或者你的资源表是固定的话,那就类似二楼的方法就可以了.
      

  5.   

    那好我建一临时表
    #tempRs(XSID,ZYID,XKID,....) 将所有资源都插入到这个表中.再如何统呢???
      

  6.   

    select a.XSName,b.XKName,c.ZYName,count(*)  as 数量
    from xs a,xk b,zy c,#tempRs d
    where d.xsid=a.xsid
    and d.xkid=b.xkid
    and d.zyid=c.zyid
    group by a.XSName,b.XKName,c.ZYName更正2楼错误(少group by):select XSName,XKName,ZYName,count(*)  as 数量
    from (
    select a.XSName,b.XKName,c.ZYName
    from xs a,xk b,zy c,yw d
    where d.xsid=a.xsid
    and d.xkid=b.xkid
    and d.zyid=c.zyid
    union all
    select a.XSName,b.XKName,c.ZYName
    from xs a,xk b,zy c,sx d
    where d.xsid=a.xsid
    and d.xkid=b.xkid
    and d.zyid=c.zyid
    union all
    select a.XSName,b.XKName,c.ZYName
    from xs a,xk b,zy c,yy d
    where d.xsid=a.xsid
    and d.xkid=b.xkid
    and d.zyid=c.zyid
    union all
    select a.XSName,b.XKName,c.ZYName
    from xs a,xk b,zy c,其它科目表 d
    where d.xsid=a.xsid
    and d.xkid=b.xkid
    and d.zyid=c.zyid
    ) as t
    group by XSName,XKName,ZYName
      

  7.   

    谢谢各位大虾,可以得到统计结果.
    还有个问题是:
    得到的结果(暂时不用资源定义表)XSName              XKName             数量
      XS1                 XK1               12
      XS1                 XK2               34
      XS1                 XK3               56
      XS2                 XK1               13
      XS2                 XK2               14
      XS2                 XK3               15
    我可不可以在数据库中实现转换为:
    XSName   XK1     XK2     XK3
      XS1     12      34      56
      XS2     13      14      15
    有什么方法吗?
    没有的话我只好在程序中实现了!我就结贴了 
      

  8.   

    这种行列转换的问题论坛上经常出现如果你的XKName 已知,可以这么写:select XSName,
    sum(case XKName when 'XK1' then 数量 else 0 end) as XK1,
    sum(case XKName when 'XK2' then 数量 else 0 end) as XK2,
    sum(case XKName when 'XK3' then 数量 else 0 end) as XK3
    from 得到的结果
    group by XSName如果你的XKName 未知,就需要动态实现,可以这么写:
    declare @sql varchar(8000)
    set @sql='select XSName'
    select @sql=@sql+',sum(case XKName when '''+rtrim(XKName)+''' then 数量 else 0 end) as ['+rtrim(XKName)+']' from 得到的结果
    group by XKName
    order by XKNameexec (@sql+' from 得到的结果 group by XSName')