sql 列转行

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 chexin
union all
SELECT yuefen, 9 as yue, "9" as b FROM chexin
union all
SELECT yuefen, 10 as yue, "10" as b FROM chexin
union all
SELECT yuefen, 11 as yue, "11" as b FROM chexin
union all
SELECT 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 chexin
union all
SELECT yuefen, 201609 as yue, "9" as b FROM chexin
union all
SELECT yuefen, 201610 as yue, "10" as b FROM chexin
union all
SELECT yuefen, 201611 as yue, "11" as b FROM chexin
union all
SELECT 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 chexin
union all
SELECT yuefen, 201609 as yue, "9" as b FROM chexin
union all
SELECT yuefen, 201610 as yue, "10" as b FROM chexin
union all
SELECT yuefen, 201611 as yue, "11" as b FROM chexin
union all
SELECT yuefen, 201612 as yue, "12" as b FROM chexin 
) chexin where yue>=201608 group by yue 

技术分享

以上是关于sql 列转行的主要内容,如果未能解决你的问题,请参考以下文章

MySQL行转列与列转行

sql语句列转行

sql列转行查询

SAS行转列&&列转行

sql列转行

SQL 列转行