首页 > 代码库 > sql 列转行

sql 列转行

创建表
    CREATE TABLE [dbo].[chexin]( [f_id] [int] IDENTITY(1,1) NOT NULL, [yuefen] [int] NOT NULL, [1] [int] NOT NULL, [2] [int] NOT NULL, [3] [int] NOT NULL, [4] [int] NOT NULL, [5] [int] NOT NULL, [6] [int] NOT NULL, [7] [int] NOT NULL, [8] [int] NOT NULL, [9] [int] NOT NULL, [10] [int] NOT NULL, [11] [int] NOT NULL, [12] [int] NOT NULL, [name] [varchar](50) NOT NULL, [gender] [varchar](20) NOT NULL, CONSTRAINT [PK__chexin__2911CBED571DF1D5] PRIMARY KEY CLUSTERED ( [f_id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO

select * from chexin   

技术分享

列转行(8月份之后的所有数据列转行)

SELECT * from(SELECT yuefen, 8 as yue, "8" as b FROM chexinunion allSELECT yuefen, 9 as yue, "9" as b FROM chexinunion allSELECT yuefen, 10 as yue, "10" as b FROM chexinunion allSELECT yuefen, 11 as yue, "11" as b FROM chexinunion allSELECT yuefen, 12 as yue, "12" as b FROM chexin ) chexin     where yuefen>=201608

技术分享

查询8月、之后所有月的合计数据(包括8月)

select a d,sda c,yuefen,name,gender ,(SELECT SUM(b) from(SELECT yuefen, 201608 as yue, "8" as b FROM chexinunion allSELECT yuefen, 201609 as yue, "9" as b FROM chexinunion allSELECT yuefen, 201610 as yue, "10" as b FROM chexinunion allSELECT yuefen, 201611 as yue, "11" as b FROM chexinunion allSELECT yuefen, 201612 as yue, "12" as b FROM chexin ) chexin     where yue>=201608 and yuefen>=201608) 合计    from chexin  where yuefen >=201608

技术分享

8月之后每个月的合计

SELECT yue,SUM(b) 合计 from(SELECT yuefen, 201608 as yue, "8" as b FROM chexinunion allSELECT yuefen, 201609 as yue, "9" as b FROM chexinunion allSELECT yuefen, 201610 as yue, "10" as b FROM chexinunion allSELECT yuefen, 201611 as yue, "11" as b FROM chexinunion allSELECT yuefen, 201612 as yue, "12" as b FROM chexin ) chexin where yue>=201608 group by yue 

技术分享

sql 列转行