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

  • 相关阅读:
    多页面通信问题
    Web Worker
    http 状态码(转载)
    如何把一个Array 复制到ArrayList中?
    使用C#数据如何导到excel
    面试题:Web Service与wcf的区别
    ASP.NET为我们提供了几种错误处理机制?
    使用sql语句创建带有输出参数的存储过程
    存储过程维护
    Linux系统下的网络配置
  • 原文地址:https://www.cnblogs.com/yangpeng-jingjing/p/4711014.html
Copyright © 2011-2022 走看看