8

我有一个带有列的表sales(int)month(int)。我想检索每个月对应的销售额总和。我需要以与每个月对应的 12 列的形式输出,其中将有一条记录包含每个列(月)的销售额。

4

5 回答 5

10

您应该看一下PIVOT以使用列切换行。这可以防止每个月的 select 语句。像这样的东西:

DECLARE @salesTable TABLE
(
    [month] INT,
    sales INT
)

-- Note that I use SQL Server 2008 INSERT syntax here for inserting
-- multiple rows in one statement!
INSERT INTO @salesTable
VALUES (0, 2) ,(0, 2) ,(1, 2) ,(1, 2) ,(2, 2)
      ,(3, 2) ,(3, 2) ,(4, 2) ,(4, 2) ,(5, 2)
      ,(6, 2) ,(6, 2) ,(7, 2) ,(8, 2) ,(8, 2)
      ,(9, 2) ,(10, 2) ,(10, 2) ,(11, 2) ,(11, 2)

SELECT [0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11]
FROM
(
    SELECT [month], sales
    FROM @salesTable
) AS SourceTable
PIVOT
(
    SUM(sales)
    FOR [month] IN ([0], [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11])
) AS PivotTable
于 2009-04-29T11:28:43.377 回答
2

这是编写枢轴的另一种方法,它可以让您获得更多控制权(尤其是对列名)。生成动态 SQL 也更容易一些。

它类似于罗宾的答案,但具有只打桌子一次的优势:

select
  Sales1 = sum( case when Month = 1 then Sales end )
, Sales2 = sum( case when Month = 2 then Sales end )
, Sales3 = sum( case when Month = 3 then Sales end )
-- etc..
from SalesTable;

我做了一些调查,似乎新的枢轴运算符只是这种查询的语法糖。查询计划最终看起来相同。

有趣的是,unpivot 运算符似乎也只是语法糖。例如:

如果你有这样的表:

Create Table Sales ( JanSales int, FebSales int, MarchSales int...)

你可以写:

 select unpivoted.monthName, unpivoted.sales
 from Sales s
 outer apply (
    select 'Jan', JanSales union all
    select 'Feb', FebSales union all
    select 'March', MarchSales
 ) unpivoted( monthName, sales );

并获取未透视的数据...

于 2009-05-01T00:17:32.690 回答
2

不漂亮......但这很好用

SELECT
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 1) [Sales1],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 2) [Sales2],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 3) [Sales3],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 4) [Sales4],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 5) [Sales5],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 6) [Sales6],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 7) [Sales7],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 8) [Sales8],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 9) [Sales9],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 10) [Sales10],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 11) [Sales11],
    (SELECT SUM(Sales) FROM SalesTable WHERE [Month] = 12) [Sales12]
于 2009-04-29T11:26:41.430 回答
1

您可以使用OLAP来完成。是有关该主题的 MSDN 文档的另一个链接。

使用 OLAP,您可以使用您拥有的信息和您需要的布局创建一个多维数据集。

如果您不想这样做,则必须使用 .NET、Java、TransacSQL 或您喜欢的语言创建汇总表来操作 SQLServer 数据。

于 2009-04-29T11:29:18.867 回答
0

要轻松地将列转换为具有其名称的行,您应该使用 XML。在我的博客中,我通过示例对此进行了描述:链接

于 2011-04-08T13:34:43.150 回答