T-SQL中带有PIVOT命令的GROUP BY语句

时间:2019-01-11 14:38:38

标签: sql sql-server tsql group-by pivot

我有一个涉及PIVOT命令的SQL查询,该命令创建了正确的表,但是现在我需要GROUP BY列之一。

当我尝试添加GROUP BY语句时,它返回以下错误:“列'PivotTable.1'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。”

SELECT [Load ID],[1],[2],[3],[4]
FROM TMS_Load_Stops
PIVOT (
    MIN([Stop Zip])
    for [Sequence] IN ([1],[2],[3],[4])
    ) PivotTable
;

原始代码产生以下结果: enter image description here

我希望结果如下(出于解释目的,值是随机数): enter image description here

3 个答案:

答案 0 :(得分:2)

如果省略Group by子句,它将自动将[Load ID]作为分组列。枢纽中有三种类型的列-分组列,聚合列和生成列。这里的分组是[Load ID],跨度是[Sequence],汇总是[Stop Zip]。 使用以下查询。

c = randomsort(exlist) # Create an instance of the object
c.scramble() # Call method scramble of instance c

答案 1 :(得分:1)

使用条件聚合。简单得多:

SELECT [Load ID],
       MIN(CASE WHEN [Sequence] = 1 THEN [Stop Zip] END) as [1],
       MIN(CASE WHEN [Sequence] = 2 THEN [Stop Zip] END) as [2],
       MIN(CASE WHEN [Sequence] = 3 THEN [Stop Zip] END) as [3],
       MIN(CASE WHEN [Sequence] = 4 THEN [Stop Zip] END) as [4],
FROM TMS_Load_Stops
GROUP BY [Load ID];

PIVOT不起作用,因为表中有其他要旋转的列。我只是不喜欢语法或其工作方式,但是您也可以通过选择所需的列来解决它:

SELECT [Load ID], [1], [2], [3], [4]
FROM (SELECT [Load ID], [Sequence], [Stop Zip]
      FROM TMS_Load_Stops
     ) ls
PIVOT (
    MIN([Stop Zip])
    for [Sequence] IN ([1],[2],[3],[4])
    ) PivotTable
;

答案 2 :(得分:1)

您必须在TMS_Load_Stops之前“投影” PIVOT中的任何其他列,因为它已经执行了分组-使用PIVOT中未提及的所有列:

SELECT [Load ID],[1],[2],[3],[4]
FROM (select [Load ID],[Sequence],[Stop Zip] from TMS_Load_Stops) t
PIVOT (
    MIN([Stop Zip])
    for [Sequence] IN ([1],[2],[3],[4])
    ) PivotTable
;