年份为Column和Fetch数据

时间:2014-03-18 13:19:06

标签: sql sql-server sql-server-2008

我在SQL Server 2008中有这样的表

SalesMonth    SalesPerson       TotalAmount
-----------   -----------       -----------
3              Ram                10000
3              Rajesh             25000
4              Rajesh             8500
6              Ram                12000
6              Anand              7000
11             Ram                6500

结果应该是......

SalesPerson   Jan  Feb   Mar      Apr     Jun     Jul     Aug     Sep     Oct    Nov    Dec
Ram            0    0    10000     0      12000    0       0       0       0     6500    0
Rajesh         0    0    25000    8500      0      0       0       0       0      0      0
Anand          0    0     0        0       7000    0       0       0       0      0      0

是否可以通过sql查询。如果是的话,请帮助我......

3 个答案:

答案 0 :(得分:0)

尝试使用PIVOT

SELECT SalesPerson, 
ISNULL([1],0) as JAN,
ISNULL([2],0) as FEB,
ISNULL([3],0) as MAR,
ISNULL([4],0) as APR,
ISNULL([5],0) as MAY,
ISNULL([6],0) as JUN,
ISNULL([7],0) as JUL,
ISNULL([8],0) as AUG,
ISNULL([9],0) as SEP,
ISNULL([10],0) as OCT,
ISNULL([11],0) as NOV,
ISNULL([12],0) as DEC

FROM t
PIVOT
(  SUM(TotalAmount)
   FOR SalesMonth IN 
       ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
) AS PivotTable
ORDER BY SalesPerson;

SQLFiddle demo

答案 1 :(得分:0)

您需要使用SQL Server的PIVOT operator

SELECT SalesPerson, [Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec]
FROM (
    SELECT MonthName.SalesMonthName, Sales.SalesPerson, Sales.TotalAmount
    FROM Sales 
    INNER JOIN MonthName ON ( MonthName.MonthNumber = Sales.SalesMonth )
) AS SourceTable
PIVOT (
    Sum(TotalAmount)
    FOR SalesMonthName IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])
) AS PivotTable

此外,由于PIVOT聚合数据,上面的示例使用Sum()函数。 (您可以根据需要轻松使用Avg()或其他聚合函数。)

对于没有值的所有元素,您的输出将 NULL

注意:在上面的例子中,我假设有一个虚构的表(MonthName)将月份数字(1,2,...)转换为月份名称(Jan,Feb,...),因为您的数据不会显示从月份数到月份名称的“跳转”。如果您不想这样做,请在上面的SQL语句中将[Jan], [Feb], ..., [Nov], [Dec]替换为[1], [2], ..., [11], [12](当然,请删除INNER JOIN)。

答案 2 :(得分:0)

SELECT   SalesPerson,
    [1] as jan, [2] as feb, [3] as mar, [4] as apr, [5] as may, [6] as jun, [7] as jul
    , [8] as aug,[9] as sept,[10] as oct,[11] as nov,[12] as decm
FROM
     table1
PIVOT
    (
    sum(TotalAmount)
    FOR SalesMonth IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])
    ) AS PivotTable;