zoukankan      html  css  js  c++  java
  • sql纵向表转成横向表

    declare @tab table(Class varchar(20),Student varchar(20),Course varchar(50),Grades decimal(7,2));
    insert into @tab(Class,Student,Course,Grades) values('A班','张三','语文',60);
    insert into @tab(Class,Student,Course,Grades) values('A班','张三','数学',70);
    insert into @tab(Class,Student,Course,Grades) values('A班','张三','英语',80);
    insert into @tab(Class,Student,Course,Grades) values('A班','李四','语文',30);
    insert into @tab(Class,Student,Course,Grades) values('A班','李四','数学',40);
    insert into @tab(Class,Student,Course,Grades) values('A班','李四','英语',50);
    insert into @tab(Class,Student,Course,Grades) values('B班','王五','语文',65);
    insert into @tab(Class,Student,Course,Grades) values('B班','王五','数学',75);
    insert into @tab(Class,Student,Course,Grades) values('B班','王五','英语',85);
    insert into @tab(Class,Student,Course,Grades) values('B班','赵六','语文',35);
    insert into @tab(Class,Student,Course,Grades) values('B班','赵六','数学',45);
    insert into @tab(Class,Student,Course,Grades) values('B班','赵六','英语',55);

    select * from @tab

    select
        (case when Grouping(Class)=1 then '总平均' when Grouping(Student)=1 then '' else Class end ) as Class
        ,(case when Grouping(Class)=1 then '' when Grouping(Student)=1 then '平均' else Student end) as Student
        ,cast(avg(语文) as decimal(7,2)) as 语文
        ,cast(avg(数学) as decimal(7,2)) as 数学
        ,cast(avg(英语) as decimal(7,2)) as 英语
        ,cast(avg(总分) as decimal(7,2)) as 总分
    from (
        select Class,Student
        ,(select isnull(sum(Grades),0) from @tab where class="t".Class and Student=t.Student and Course='语文') as '语文'
        ,(select isnull(sum(Grades),0) from @tab where class="t".Class and Student=t.Student and Course='数学') as '数学'
        ,(select isnull(sum(Grades),0) from @tab where class="t".Class and Student=t.Student and Course='英语') as '英语'
        ,(select isnull(sum(Grades),0) from @tab where class="t".Class and Student=t.Student) as '总分'
        from @tab as t
        group by Class,Student
        ) as tempTab
    group by Class,Student,语文,数学,英语,总分 with rollup
    having Grouping(语文)=1
        and Grouping(数学)=1
        and Grouping(英语)=1

  • 相关阅读:
    【USACO1.6.3】Prime Palindromes【数论,数学】【模拟】
    【HDU6345】子串查询【前缀和】【线段树】
    【HDU6345】子串查询【前缀和】【线段树】
    【HDU6344】调查问卷【状压】【模拟】
    【HDU6344】调查问卷【状压】【模拟】
    获取一个处理程序函数到一个特定的弹出菜单
    一个剪贴板增强工具
    将checklistbox控件与DataView绑定
    探索者命令式的三分
    ColorListBox
  • 原文地址:https://www.cnblogs.com/weipeng/p/2651188.html
Copyright © 2011-2022 走看看