• SQL 的多列统计


    create table #type(id int , type varchar(30))
    insert into #type
    select  1  ,'中国'
    union
    select 2  ,'美国'
    union
    select 3 , '俄罗斯'

    create table #timu(id int ,typeid int ,score int )
    insert into #timu
    select         1    ,    1    ,    3
    union select 2    ,    1    ,    4
    union select 3    ,    1    ,    5
    union select 4    ,    2    ,    3
    union select 5    ,    2    ,    4
    union select 6    ,    3    ,    5

    create table #paper(id int ,qid int   )
    insert into #paper
    select            1 , 1
    union select    1 , 2
    union select    1 , 3
    union select    1 , 5
    union select    2 ,1
    union select    2 ,2
    union select    2 ,6

    select  p.id ,  sum(china.score) as 中国 , sum(am.score) as 美国 , sum(a.score) as  俄罗斯
    from #paper as p
    left join (select id ,score from #timu where typeid =1 ) as china on ( p.qid = china.id )
    left join (select id ,score from #timu where typeid =2 ) as am on ( p.qid = am.id )
    left join (select id ,score from #timu where typeid =3 ) as a on ( p.qid = a.id )
    group by p.id

    select  *
    from #paper as p
    --join (select id ,score from #timu where typeid =1 ) as china on ( p.qid = china.id )
    join (select id ,score from #timu where typeid =2 ) as am on ( p.qid = china.id )
    join (select id ,score from #timu where typeid =3 ) as a on ( p.qid = china.id )
    group by p.id


    结果:

    id          中国          美国          俄罗斯
    ----------- ----------- ----------- -----------
    1           12          4           NULL
    2           7           NULL        5
    警告: 聚合或其他 SET 操作消除了空值。

    (2 行受影响)


  • 相关阅读:
    python核心编程课后题第二版36页第二章
    Python每个N个字符插入一个符号
    python核心编程课后题第二版97页第五章
    意外的 404 错误
    WCF简单使用(分别部署在控制台和IIS上)
    最近看的项目cakephp
    我正在翻译的CakePHP manual
    C# 高质量编程
    Android 环境搭建
    MVC 读配置文件 多语言
  • 原文地址:https://www.cnblogs.com/newsea/p/990059.html
Copyright © 2020-2023  润新知