MaoBisheng

Asp.Net(C#) & SQL & Oracle

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

准备测试表和测试数据:

   1: CREATE TABLE [dbo].[StateLog](
   2:     [ID] [int] IDENTITY(1,1) NOT NULL,
   3:     [State] [int] NULL,
   4:     [CreateDate] [datetime] NULL
   5: ) ON [PRIMARY]
   6:  
   7: GO
   8:  
   9: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('0','2012-03-05')
  10: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('2','2012-03-05')
  11: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('3','2012-03-05')
  12: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('1','2012-03-05')
  13: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('1','2012-03-05')
  14: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('1','2012-03-05')
  15: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('1','2012-03-06')
  16: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('2','2012-03-06')
  17: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('2','2012-03-06')
  18: INSERT INTO [dbo].[StateLog]([State],[CreateDate]) VALUES ('2','2012-03-06')

需要统计每天的总数以及各个状态有多少数量:

hlzh02

 

SQL语句如下:

   1: select A.CreateDate,B.TotalQty,A.State0,A.State1,A.State2,A.State3 from 
   2: (
   3:     --行列转换,核心
   4:     SELECT [0][State0],[1][State1],[2][State2],[3][State3],CreateDate FROM 
   5:     (
   6:         SELECT MAIN.[State],[StateLog].CreateDate 
   7:         FROM [StateLog] MAIN JOIN [StateLog] ON MAIN.CreateDate=[StateLog].CreateDate
   8:         WHERE MAIN.[State] IN (0,1,2,3) 
   9:             AND [StateLog].[State] IN (0,1,2,3) 
  10:             AND MAIN.[State]<>[StateLog].[State]
  11:         GROUP BY MAIN.ID,MAIN.[State],[StateLog].CreateDate
  12:     ) G
  13:     PIVOT
  14:     (
  15:         COUNT([State]) 
  16:         FOR [State] IN ([0],[1],[2],[3])
  17:     )P
  18: ) A,
  19: (
  20:     --计算总数
  21:     SELECT COUNT(1) as TotalQty, CreateDate
  22:     FROM [dbo].[StateLog]
  23:     group by CreateDate
  24: ) B
  25: where A.CreateDate=B.CreateDate
posted on 2012-05-18 13:50  MaoBisheng  阅读(394)  评论(0编辑  收藏  举报