码迷,mamicode.com
首页 > 数据库 > 详细

MSSQL纵列转横列

时间:2015-10-14 21:35:38      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:

   上篇我们说到了横列转纵列,下面就来说下纵列转横列

   1.建表

CREATE TABLE [dbo].[EndLongChangeAcross](
    [Id] [INT] IDENTITY(1,1) NOT NULL,
    [Name] [NVARCHAR](50) NOT NULL,
    [Chinese] [INT] NOT NULL,
    [English] [INT] NOT NULL,
    [Math] [INT] NOT NULL,
 CONSTRAINT [PK_EndLongChangeAcross] PRIMARY KEY CLUSTERED 
(
    [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

ALTER TABLE [dbo].[EndLongChangeAcross] ADD  CONSTRAINT [DF_EndLongChangeAcross_Chinese]  DEFAULT ((0)) FOR [Chinese]
GO

ALTER TABLE [dbo].[EndLongChangeAcross] ADD  CONSTRAINT [DF_EndLongChangeAcross_English]  DEFAULT ((0)) FOR [English]
GO

ALTER TABLE [dbo].[EndLongChangeAcross] ADD  CONSTRAINT [DF_EndLongChangeAcross_Math]  DEFAULT ((0)) FOR [Math]
GO

2.具体SQL

SELECT  Name ,
        语文 AS Subject,
        Chinese AS Score
FROM    dbo.EndLongChangeAcross
UNION ALL
SELECT  Name ,
        英语,
        English AS Score
FROM    dbo.EndLongChangeAcross
UNION ALL
SELECT  Name ,
        数学 ,
        Math AS Score
FROM    dbo.EndLongChangeAcross
ORDER BY Name DESC

具体效果:

技术分享

MSSQL纵列转横列

标签:

原文地址:http://www.cnblogs.com/zuqing/p/4878823.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!