USE [ExampleDb] GO /****** Object: Table [dbo].[PivotDemo1] Script Date: 2017/12/16 14:12:46 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[PivotDemo1]( [Id] [int] IDENTITY(1,1) NOT NULL, [WarehouseType] [nvarchar](50) NOT NULL CONSTRAINT [DF_Table_1_FType] DEFAULT (‘‘), [Warehouse] [nvarchar](50) NOT NULL CONSTRAINT [DF_Demo_B仓库] DEFAULT (‘‘), [Number] [int] NOT NULL CONSTRAINT [DF_Demo_C数量] DEFAULT ((0)), CONSTRAINT [PK_Demo] 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].[PivotDemo1] ON INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (1, N‘AH125‘, N‘S库‘, 100) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (2, N‘AH125‘, N‘H库‘, 200) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (3, N‘AH125‘, N‘A库‘, 300) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (4, N‘AH125‘, N‘B库‘, 400) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (5, N‘AH126‘, N‘S库‘, 100) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (6, N‘AH126‘, N‘H库‘, 300) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (7, N‘AH126‘, N‘A库‘, 500) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (8, N‘AH126‘, N‘B库‘, 700) INSERT [dbo].[PivotDemo1] ([Id], [WarehouseType], [Warehouse], [Number]) VALUES (9, N‘AH127‘, N‘B库‘, 700) SET IDENTITY_INSERT [dbo].[PivotDemo1] OFF -------------------------------------------------------------------------------------- select [Id] , [WarehouseType] , [Warehouse] , [Number] from [ExampleDb].[dbo].[PivotDemo1]; -------------------------------------------------------------------------------------- select * from ( select Number , Warehouse , WarehouseType from ExampleDb.dbo.PivotDemo1 ) p pivot ( sum(Number) for Warehouse in ( S库, H库, A库, B库 ) ) as pvt order by pvt.WarehouseType; -------------------------------------------------------------------------------------- with a as ( select WarehouseType , S库 , H库 , A库 , B库 from ( select Number , Warehouse , WarehouseType from ExampleDb.dbo.PivotDemo1 ) p pivot ( sum(Number) for Warehouse in ( S库, H库, A库, B库 ) ) as pvt ), b as ( select WarehouseType as mo , sum(Number) as total from ExampleDb.dbo.PivotDemo1 group by WarehouseType ) select a.* , b.total from a join b on a.WarehouseType = b.mo; --------------------------------------------------------------------------------------