首页 > 代码库 > 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 列转行
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。