USE [ExampleDb]
GO
/****** Object: Table [dbo].[SalesInfo1] Script Date: 2017/12/16 13:38:19 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[SalesInfo1](
[Make] [nvarchar](50) NOT NULL CONSTRAINT [DF_SalesInfo_Make] DEFAULT (''),
[Year] [int] NOT NULL CONSTRAINT [DF_SalesInfo_Year] DEFAULT ((0)),
[Sales] [int] NOT NULL CONSTRAINT [DF_SalesInfo_Sales] DEFAULT ((0)),
[Id] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_SalesInfo] 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
SET IDENTITY_INSERT [dbo].[SalesInfo1] ON
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Honda', 1990, 2000, 1)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Honda', 1990, 1000, 2)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Acura', 1990, 500, 3)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Honda', 1991, 3000, 4)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Acura', 1991, 300, 5)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Acura', 1991, 600, 6)
INSERT [dbo].[SalesInfo1] ([Make], [Year], [Sales], [Id]) VALUES (N'Acura', 1991, 800, 7)
SET IDENTITY_INSERT [dbo].[SalesInfo1] OFF
--------------------------------------------------------------------------------------------
select [Make] ,
[Year] ,
[Sales] ,
[Id]
from [ExampleDb].[dbo].[SalesInfo1];
---------------------------------------------------------------------------------------------
--Step 1
select t.Make ,
[1990] ,
[1991]
from dbo.SalesInfo1 pivot ( sum(Sales) for Year in ( [1990], [1991] ) ) t;
--Step 2
select tmp.Make ,
sum(tmp.[1990]) [1990] ,
sum(tmp.[1991]) [1991]
from ( select t.Make ,
[1990] ,
[1991]
from dbo.SalesInfo1 pivot ( sum(Sales) for Year in ( [1990],
[1991] ) ) t
) tmp
group by tmp.Make;
---------------------------------------------------------------------------------------------
select *
from ( select Make ,
Year ,
Sales
from dbo.SalesInfo1
) tmp pivot ( sum(Sales) for Year in ( [1990], [1991] ) ) t;
--复制表
select [Make] ,
[Year] ,
[Sales]
into [ExampleDb].[dbo].SalesInfo2
from [ExampleDb].[dbo].SalesInfo1;
--Step 1
select t.Make ,
[1990] ,
[1991]
from dbo.SalesInfo2 pivot ( sum(Sales) for Year in ( [1990], [1991] ) ) t;