如何为这个逻辑编写sql?

时间:2012-02-10 15:37:48

标签: sql-server sql-server-2008

我有以下表格(缩写)

tableAssignments
    id
    timestamp             // updated when row is modified
    tableSystems
    tableUsers
    ...

tableAssignmentsSnapshot
    id
    timestamp             // set when row created, snapshots never change
    tableSystemsSnapshot
    tableUsersSnapshot
    tableAssignments_id   // reference to "tableAssignments" row this was created from
    syncKey               // Changed when snapshots are created, max value is latest

更改tableAssignments后的某个时间,将执行所有分配的快照,并使用相同的syncKey创建快照。我正在尝试编写一个查询来检查最新的“tableAssignmentsSnapshot”是否是最新的,或者是否应该采用新的。所需的逻辑是:

  1. 确定每个系统的最新tableAssignmentSnapshots,由最大syncKey确定(请参阅下面的查询)。

  2. 使用tableAssignments加入#1的结果。

  3. 如果来自tableAssignments的时间戳> tableAssignmentsSnapshot的时间戳然后需要新的快照。

  4. 以下查询完成步骤#1并快速运行。它返回tableAssignmentSnapshots,每个系统的最大值为“syncKey”。

    select * from
        tableAssignmentsSnapshot d inner join tableSystemsSnapshot e
        on d.systemId = e.id
        where d.syncKey = (select MAX(syncKey) from tableAssignmentsSnapshot y inner join tableSystemsSnapshot z
      on y.systemId = z.id
       where tableSystems_id = e.tableSystems_id)
    

    我正在努力做下一步该做什么。我需要能够执行以下操作,但遇到所需语法的问题:

    select * from tableAssignments a right outer join
    (
        the result from above query
    )
    on a.id = ?.tableAssignments_id
    

1 个答案:

答案 0 :(得分:0)

您可以将您的第一个查询包装在CTE上:

;WITH CTE AS
(
    SELECT * -- Here you should list only the columns that you are gonna need
    FROM tableAssignmentsSnapshot D
    INNER JOIN tableSystemsSnapshot E
        ON D.systemId = E.id
    WHERE D.syncKey = ( select MAX(syncKey) from tableAssignmentsSnapshot y inner join tableSystemsSnapshot z
                        on y.systemId = z.id
                        where tableSystems_id = e.tableSystems_id)
)

SELECT * 
FROM tableAssignments A
RIGHT JOIN CTE B
ON A.id = B.tableAssignments_id
相关问题