zoukankan      html  css  js  c++  java
  • sql 列转行 实例

     select * from dbo.orders  group by  custid  with cube    select custid ,row_number() over(order by empid) as number from  orders    select count(*) from orders where empid >'5' and orderid in ('10248','10249')    drop table test  create table test(id int,name varchar(20),quarter int,profile int) insert into test values(1,'a',1,1000) insert into test values(1,'a',2,2000) insert into test values(1,'a',3,4000) insert into test values(1,'a',4,5000) insert into test values(2,'b',1,3000) insert into test values(2,'b',2,3500) insert into test values(2,'b',3,4200) insert into test values(2,'b',4,5500) select * from test

    select id,name, [1] as "一季度", [2] as "二季度", [3] as "三季度", [4] as "四季度", [5] as "5" from test pivot ( sum(profile) for quarter in ([1],[2],[3],[4],[5]) ) as pvt CREATE TABLE [dbo].[TestRows2Columns](     [Id] [int] IDENTITY(1,1) NOT NULL,     [UserName] [nvarchar](50) NULL,     [Subject] [nvarchar](50) NULL,     [Source] [numeric](18, 0) NULL ) ON [PRIMARY] GO

    --插入测试数据 INSERT INTO [TestRows2Columns] ([UserName],[Subject],[Source])     SELECT N'张三',N'语文',60  UNION ALL     SELECT N'李四',N'数学',70  UNION ALL     SELECT N'王五',N'英语',80  UNION ALL     SELECT N'王五',N'数学',75  UNION ALL     SELECT N'王五',N'语文',57  UNION ALL     SELECT N'李四',N'语文',80  UNION ALL     SELECT N'张三',N'英语',100 GO

    SELECT * FROM [TestRows2Columns]

    select username , sum(case[subject] when '数学' then source else  0 end) as '[数学]', sum(case[subject] when '英语' then source else  0 end) as '[英语]', sum(case[subject] when '语文' then source else  0 end) as '[语文]' from [TestRows2Columns] group by username

    select * from (select username,subject,source from TestRows2Columns)p pivot (sum (source) for subject in ([数学],[英语],[语文] )) as v order by v.username

  • 相关阅读:
    CentOS 5.5 Oracle 11g
    安装VMware后,设置WinRM
    Scientific linux 6 使用第三方软件仓库(转)
    ASP.NET 标签问题
    《Linux网络编程》读书笔记
    基本通信模型
    SQL Server中的自增长
    windows平台通信基础
    线程学习小结
    SQL Server中添加注释
  • 原文地址:https://www.cnblogs.com/yangpeng-jingjing/p/4711014.html
Copyright © 2011-2022 走看看