选择MONTH()的PIVOT

时间:2016-05-26 06:42:15

标签: sql pivot

如何以日期为MONTH的列作为参数进行数据透视?

示例:

数据:

|-----------------------------------|
| def_kstnr | def_zeit | def_datum  |
|-----------------------------------|
| 100       | 3.2      | 2011-11-02 |
| 110       | 2.8      | 2011-02-03 |
| 120       | 5.4      | 2011-11-04 |
| 130       | 2.4      | 2011-08-05 |
| 140       | 4.9      | 2011-09-06 |
| 150       | 1.5      | 2011-10-07 |
| 160       | 2.6      | 2011-12-08 |
|-----------------------------------|

查询:

SELECT
    def_kstnr,
    [1] AS Jan,
    [2] AS Feb,
    [3] AS Mrz,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Okt,
    [11] AS Nov,
    [12] AS Dez
FROM
(Select 
def_kstnr,
def_zeit,
 MONTH(def_datum) as TMonth
  from
    dbo.def) source
PIVOT
(
    SUM(def_zeit)
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

如果参数month = 2(February):

,结果应该如下所示
| def_kstnr  |  Feb |
   110          2.8

如果参数month = 11(11月)

| def_kstnr  |  Nov |
   100          3.2

我已经在谷歌搜索,但我不知道这个案例的关键字是什么。我还没有找到它。谢谢..

1 个答案:

答案 0 :(得分:0)

如果您正在使用SQL Server,则可以创建一个像这样的动态SQL

DECLARE @Month Int = 11,
        @MonthName VARCHAR(20),
        @Sql NVARCHAR(MAX)

SET     @MonthName = CONVERT(VARCHAR(3), DATEADD(Month, @Month, -1), 107)
SET     @Sql = N'   SELECT  def_kstnr, 
                            def_zeit AS ' + QUOTENAME(@MonthName) + '
                    FROM    DataTable
                    WHERE   MONTH([def_datum]) = @Month'

EXEC sp_executesql @Sql, N'@Month INT', @Month = @Month 

您可以将SUM(def_zeit)GROUP BY def_kstnr添加到动态sql,如果这是您的结果...很难说出您的预期结果