PIvot查询月份sql server 2008

时间:2014-10-29 09:37:41

标签: sql-server vb.net

SELECT
    RNAME,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Oct
  FROM
(Select 
RNAME,
BILLAMT,
 DATEPART(mm,DATE1) as TMonth
  from
    #temp 
PIVOT
(
    SUM(BILLAMT)
    FOR TMonth
    IN ([4],[5],[6],[7],[8],[9],[10])
)AS pvtMonth

这是我的查询。我在这个查询中遇到错误。

我需要为rname显示monthwise billamount。请帮助找出错误。 'pvtMonth'附近的语法不正确。 这是表格的结构

rname | billamt | date1 | aaa | 400 | 2014年1月4日| bbb | 200 | 23-3-2014 | bbb | 500 | 12-04-2014 |

| 100 | 1-04-2014 |

我需要这样的 姓名| mar |四月 aaa | 400 | 0 bbb | 200 | 500        | 0 | 100

1 个答案:

答案 0 :(得分:0)

试试这个{错过关闭大括号别名 inner query

SELECT RNAME,
       [4]  AS Apr,
       [5]  AS Mai,
       [6]  AS Jun,
       [7]  AS Jul,
       [8]  AS Aug,
       [9]  AS Sep,
       [10] AS Oct
FROM   (SELECT RNAME,
               BILLAMT,
               Datepart(mm, DATE1) AS TMonth
        FROM   #temp) a -- this is what u missed
       PIVOT ( Sum(BILLAMT)
             FOR TMonth IN ([4],
                            [5],
                            [6],
                            [7],
                            [8],
                            [9],
                            [10]) )AS pvtMonth