USE [ExampleDb]
GO
/****** Object: Table [dbo].[PivotDemo2] Script Date: 2017/12/16 14:44:52 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[PivotDemo2](
[Id] [int] IDENTITY(1,1) NOT NULL,
[PDate] [nvarchar](50) NOT NULL CONSTRAINT [DF_ResultInfo_Date] DEFAULT (''),
[PResult] [nvarchar](50) NOT NULL CONSTRAINT [DF_ResultInfo_Result] DEFAULT (''),
CONSTRAINT [PK_ResultInfo] 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].[PivotDemo2] ON
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (1, N'2017-10-10', N'优')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (2, N'2017-10-10', N'优')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (3, N'2017-10-10', N'良')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (4, N'2017-10-10', N'良')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (5, N'2017-10-11', N'优')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (6, N'2017-10-11', N'优')
INSERT [dbo].[PivotDemo2] ([Id], [PDate], [PResult]) VALUES (7, N'2017-10-11', N'良')
SET IDENTITY_INSERT [dbo].[PivotDemo2] OFF
--------------------------------------------------------------------------------------------------
select [Id] ,
[PDate] ,
[PResult]
from [ExampleDb].[dbo].[PivotDemo2];
--------------------------------------------------------------------------------------------------
select tmp.PDate ,
sum([优]) 优 ,
sum([良]) 良
from ( select [PDate] ,
case PResult
when '优' then count(1)
else 0
end '优' ,
case PResult
when '良' then count(1)
else 0
end '良'
from [ExampleDb].[dbo].[PivotDemo2]
group by PDate ,
PResult
) tmp
group by tmp.PDate;
--------------------------------------------------------------------------------------------------
select cctable.PDate ,
sum(cctable.优) '优' ,
sum(cctable.良) '良'
from ( select ctable.PDate ,
case ctable.PResult
when '优' then ctable.rum
else 0
end '优' ,
case ctable.PResult
when '良' then ctable.rum
else 0
end '良'
from ( select case a.PResult
when '优' then '优'
else '良'
end as PResult ,
count(a.PResult) rum ,
a.PDate
from ExampleDb.[dbo].[PivotDemo2] a with ( nolock )
group by a.PDate ,
a.PResult
) ctable
) cctable
group by cctable.PDate;
--------------------------------------------------------------------------------------------------