例如
month1 month2 month3 total district1 5 2 9 16 district2 1 0 11 12 . . total 260 150 140 550
这里的最终总数并不重要。但至少我需要显示每个区每月的计数。
SELECT Districts_mst.district_name,COUNT(Payments.PaymentId)users ,DATEPART(M,payments.saveon)Month FROM Payments JOIN Subsciber ON Payments.SubId =Subsciber.SubId JOIN districts_mst ON districts_mst.district_id = Subsciber.District where lang_id=1 group by district_name, DATEPART(M,payments.saveon)
给我的清单像.....
district_name users Month dist0 1 1 dist1 1 11 dist2 3 11 dist3 1 11 dist4 3 11 dist5 1 12 dist6 1 12
在SQL Server 2008中,您可以使用PIVOT查询轻松地完成此任务。以下示例依赖于将数据转换为以下格式(看起来已经完成了):
Name Month Value ---------- ------- ----- District 1 Month 1 10 District 1 Month 2 5 District 1 Month 3 6 District 2 Month 1 1 District 2 Month 2 2 District 2 Month 3 3 District 3 Month 1 8 District 3 Month 2 6 District 3 Month 3 11
如果可以这样做,那么您的PIVOT查询应如下所示:
DECLARE @myTable AS TABLE([Name] VARCHAR(20), [Month] VARCHAR(20), [Value] INT) INSERT INTO @myTable VALUES ('District 1', 'Month 1', 10) INSERT INTO @myTable VALUES ('District 1', 'Month 2', 5) INSERT INTO @myTable VALUES ('District 1', 'Month 3', 6) INSERT INTO @myTable VALUES ('District 2', 'Month 1', 1) INSERT INTO @myTable VALUES ('District 2', 'Month 2', 2) INSERT INTO @myTable VALUES ('District 2', 'Month 3', 3) INSERT INTO @myTable VALUES ('District 3', 'Month 1', 8) INSERT INTO @myTable VALUES ('District 3', 'Month 2', 6) INSERT INTO @myTable VALUES ('District 3', 'Month 3', 11) SELECT [Name], [Month 1], [Month 2], [Month 3], [NameTotalValue] AS [Total] FROM ( SELECT [Name], [Month], [Value], SUM([Value]) OVER (PARTITION BY [Name]) as [NameTotalValue] FROM @myTable UNION SELECT 'Total', [Month], SUM([Value]), (SELECT SUM([Value]) FROM @myTable) FROM @myTable GROUP BY [Month] ) t PIVOT ( SUM([Value]) FOR [Month] IN ([Month 1], [Month 2], [Month 3]) ) AS pvt ORDER BY pvt.[Name]
在此示例中,我使用SUM([Value]) OVER PARTITION来获取每个区的总和,然后执行UNION在底部添加总计行。结果看起来像这样:
SUM([Value]) OVER PARTITION
Name Month 1 Month 2 Month 3 Total ----------- ------- ------- ------- ----- District 1 10 5 6 21 District 2 1 2 3 6 District 3 8 6 11 25 Total 19 13 20 52
您会注意到这种方法的一件事是,您必须提前知道想要在表顶部的列名称。如果要将报告设置为全年运行,这很容易做到,但是如果要更改的列数则比较麻烦。如果要允许用户指定自定义日期范围(即07/ 2011-10 / 2011或06 / 2011-11 / 2011),则处理此要求的一种方法是使用动态SQL构建PIVOT查询然后使用sp_executesql执行它。