准备测试表和测试数据:
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')
需要统计每天的总数以及各个状态有多少数量:
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
作者:MaoBisheng
出处:http://maobisheng.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://maobisheng.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。