Home  >  Article  >  Database  >  跪求sql server2012行转列方案

跪求sql server2012行转列方案

WBOY
WBOYOriginal
2016-06-07 16:22:541236browse

下面为表创建代码: CREATE TABLE [dbo].[ProductAuditRecord]([ParID] [nchar](12) NOT NULL,[MOID] [nchar](12) NOT NULL,[LotSN] [nvarchar](50) NOT NULL,[CosmeticInspection] [nchar](12) NOT NULL,[FunctionalTest] [nchar](12) NOT NULL,[UNumber] [

   下面为表创建代码:

  CREATE TABLE [dbo].[ProductAuditRecord]([ParID] [nchar](12)

  NOT NULL,[MOID] [nchar](12)

  NOT NULL,[LotSN] [nvarchar](50)

  NOT NULL,[CosmeticInspection] [nchar](12)

  NOT NULL,[FunctionalTest] [nchar](12)

  NOT NULL,[UNumber] [nchar](50)

  NULL,[LeadWire] [nchar](50)

  NULL,[ResourceID] [nchar](12)

  NOT NULL,[UserID] [nchar](12)

  NOT NULL,[Remark] [nvarchar](100)

  NULL,[CreatDate] [datetime] NOT NULL,[ProductID] [nchar](12)

  NOT NULL,[nextID] [int] NOT NULL, CONSTRAINT [PK_ProductAuditRecord] PRIMARY KEY CLUSTERED

  ([ParID] ASC)WITH

  (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,

  IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,

  ALLOW_PAGE_LOCKS = ON) ON [PRIMARY])

  ON [PRIMARY]GOALTER TABLE [dbo].[ProductAuditRecord] ADD

  CONSTRAINT [DF_ProductAuditRecord_ParID] DEFAULT

  (substring(CONVERT([char](36),

  newid(),,(0)),(1),(12)))

  FOR [ParID]GOALTER TABLE [dbo].

  [ProductAuditRecord] ADD CONSTRAINT

  [DF_ProductAuditRecord_nextID] DEFAULT

  ((0))

  FOR [nextID]GO

  下面为自己测试数据得到的结果:上面为原始数据,下面为转换后的数据:转换代码

  测试表代码:CREATE TABLE [dbo].[Test](

  [月份] [varchar](4) NULL,

  [工资] [int] NULL,

  [福利] [int] NULL,

  [奖金] [int] NULL

  ) ON [PRIMARY]

  1:月份 工资 福利 奖金

  1月 100 200 300

  2月 110 210 310

  3月 120 220 320

  4月 130 230 330

  2:考核月份 1月 2月 3月 4月

  福利 200 210 220 230

  工资 100 110 120 130

  奖金 300 310 320 330

  SELECT * FROM

  (

  SELECT 考核月份,月份,金额 FROM

  (SELECT 月份, 工资, 福利, 奖金 FROM Test) p

  UNPIVOT

  (金额 FOR 考核月份 IN (工资, 福利, 奖金))AS unpvt

  ) T

  PIVOT

  (MAX(金额) FOR 月份 in ([1月],[2月],[3月],[4月]))AS pt

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn