如何构建一个SELECT行到SQL列的查询?

时间:2015-11-25 19:11:54

标签: sql sql-server

如何在SQL Server中编写一个查询,为每个唯一ID的每个变量返回一列?下面是我想要完成的一个简化示例。你能指出我正确的方向吗?

Table_Exists

ID    |    LOCATION    |    STATUS
__________________________________
001   |     top        |     3
001   |     mid        |     1
001   |     bot        |     4
002   |     top        |     2
002   |     mid        |     2
002   |     bot        |     1
003   |     top        |     1
003   |     mid        |     4
003   |     bot        |     2

这是我正在尝试的一个简化示例,显然没有成功。下面的代码返回错误消息,指出'='周围的语法不正确:

SELECT  
  ID,
  LOCATION = top AS Top,
  LOCATION = mid AS Middle,
  LOCATION = bot AS Bottom
FROM 
  Table_Exists

我试图建立:

Table_Desired

ID | Top | Middle | Bottom 
__________________________
001|  3  |   1    |  4
002|  4  |   2    |  2 
003|  1  |   4    |  2

2 个答案:

答案 0 :(得分:3)

您可以使用自加入(只要您的LOCATIONNOT NULL并且它包含所有top/mid/bot值):

 SELECT t1.ID, t1.Status AS Top, t2.Status AS Middle, t3.Status AS Bottom
 FROM Table_Exists t1
 JOIN Table_Exists t2
   ON t1.ID = t2.ID
  AND t1.LOCATION = 'top'
  AND t2.Location = 'mid'
 JOIN Table_Exists t3
   ON t1.ID = t3.ID
  AND t1.LOCATION = 'top'
  AND t3.Location = 'bot';

LiveDemo

对于更通用的解决方案,请使用PIVOT

SELECT
     [ID]
    ,[Top]    = [top] 
    ,[Middle] = [mid]
    ,[Bottom] = [bot]
FROM #Table_Exists t
PIVOT (
   MAX(STATUS) FOR LOCATION IN ([top],[mid],[bot])
) AS Piv

LiveDemo2

答案 1 :(得分:2)

使用像这样的枢轴功能

SELECT
    ID,
    [top] AS [Top],
    [mid] AS Middle,
    [bot] AS Bottom
FROM(SELECT 
    ID, 
    LOCATION,
    STATUS
FROM 
    Table_Exists) AS SourceTable
PIVOT (AVG(STATUS) FOR LOCATION IN ([top],[mid],[bot])) AS PivotTable