Temp Table

时间:2016-06-09 18:48:35

标签: sql tsql join sql-server-2012 temp-tables

我正在尝试使用对表的自引用在SQL Server Management Studio中添加计算列。

我的专栏如下:

[Employee ID]   [Previous State Date]    [Previous State] 
                [Next State Date]        [Next State]

我想添加一个显示第三个状态的列(发生在[Next State]列之后)。例如,如果某人来自州a - > b - > c,会有两行:

[Employee 1][1/1/2016][a][1/2/2016][b]
[Employee 1][1/2/2016][b][1/3/2016][c]

我希望数据只显示:

[Employee 1][1/1/2016][a][1/2/2016][b][c]

为此,我创建了两列,[PreviousID][NextID],用于连接州,日期和员工ID。

我想使用临时表来引入temp.[Next State] WHERE table.[Next State] = temp.[Previous State]

的新列

当我尝试这个时,我收到错误:

  

在此上下文中不允许使用子查询。只允许使用标量表达式。

我的代码:

SELECT * INTO #temp FROM table

ALTER TABLE table 
ADD [Next Next State] AS (SELECT [Next State] 
                          FROM temp  
                          WHERE table.[Next State] = temp.[Previous State])

1 个答案:

答案 0 :(得分:1)

忘记临时表并使用带有聚合函数和CTE的GROUP BY查询。类似的东西:

WITH EarliestLastChanges(EmployeeID, EarliestStateChange, LatestStateChange)
AS
(SELECT
    [Employee ID] AS EmployeeID,
    MIN([Previous State Date]) AS EarliestStateChange
    MAX([Next State Date]) AS LatestStateChange
FROM
    table
GROUP BY
    [Employee ID])
SELECT
    ELC1.EmployeeID,
    Concatenated field for Earliest from T1,
    Concatenated field for Latest from T2
FROM
   EarliestLastChanges AS ELC1
   JOIN
   table as T1
   ON ELC1.EmployeeID = T1.[Employee ID] AND ELC1.EarliestStateChange = T1.[Previous State Date]
   EarliestLastChanges AS ELC2
   JOIN
   table as T2
   ON ELC2.EmployeeID = T2.[Employee ID] AND ELC2.EarliestStateChange = T2.[Next State Date]

我同意上面的评论,重新设计将是一个更好的方式