为什么使用SQL Pivot出现语法错误?

时间:2019-05-28 15:41:55

标签: sql pivot

我在1月1日收到语法错误。

我的SampleStart是日期时间格式。我是在给错误别名吗?

SELECT * FROM (
  SELECT year(SampleStart) year, month(SampleStart) month, AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT (
  max(AllowedPopulation) 
  FOR month in (
    1 JAN, 2 FEB, 3 MAR, 4 APR, 5 MAY, 6 JUN,
    7 JUL, 8 AUG, 9 SEP, 10 OCT, 11 NOV, 12 DEC
  )
)
ORDER BY year DESC

我希望结果能向我显示2018年每个月的允许人口。

2 个答案:

答案 0 :(得分:2)

尝试-

SELECT  year,
[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 SEP,
[10] AS OCT,
[11] AS NOV,
[12] AS DEC


FROM 
(
    SELECT year(SampleStart) year, 
    month(SampleStart) month, 
    AllowedPopulation
    FROM BIC_AGGREGATE_FINAL
    WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) as s
PIVOT 
(
max(AllowedPopulation) 
FOR month in (
    [1], [2], [3], [4], [5], [6],
    [7], [8], [9], [10], [11], [12]
)
)AS PVT
ORDER BY year DESC

答案 1 :(得分:0)

您无法在数据透视功能中提供列别名,您必须在select中执行此操作。另外,在枢轴内指定IN子句时,必须选择与选择列时类似的规则,如果列是保留字,或包含特殊字符(例如空格),或以数字开头,则必须将名称括在方括号中。

最后,您必须给数据透视函数本身一个别名。

例如

SELECT  pvt.[year],
        JAN = pvt.[1],
        FEB = pvt.[2],
        MAR = pvt.[3],
        APR = pvt.[4],
        MAY = pvt.[5],
        JUN = pvt.[6],
        JUL = pvt.[7],
        AUG = pvt.[8],
        SEP = pvt.[9],
        OCT = pvt.[10],
        NOV = pvt.[11],
        DEC = pvt.[12]
FROM (
  SELECT YEAR(SampleStart) AS [year], MONTH(SampleStart) AS [month], AllowedPopulation
  FROM BIC_AGGREGATE_FINAL
  WHERE SampleStart BETWEEN '2018-01-01' AND '2018-12-31'
) AS s
PIVOT (
  MAX(AllowedPopulation) 
  FOR month IN ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]) 
) AS pvt -- Alias here too
ORDER BY pvt.[year] DESC

如果(如问题所述,SampleStartDATETIME列,那么我将对您的where子句进行两项更改:

  1. 使用专用日期范围代替BETWEEN-What do BETWEEN and the devil have in common?
  2. 使用明确的日期文字格式yyyyMMdd,具体取决于您的设置2018-10-01可以是1月10日还是10月1日。

所以您最终会得到:

   WHERE SampleStart >= '20180101' 
   AND SampleStart < '20190101'