我希望以表格格式选择查询结果,如摘要报告

时间:2011-11-30 05:08:16

标签: sql sql-server vb.net sql-server-2008

for examaple

           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

1 个答案:

答案 0 :(得分:3)

在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来向底部添加一个总计行。结果如下所示:

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执行它。