在SQL子查询中使用多个列

时间:2013-02-20 18:14:58

标签: sql sql-server

我的设置是我有两个表,Study和Activity_History。活动在研究中进行,因此存在1:多关系。

我希望能够在Activity_History表上运行SQL查询,该表将获取活动和之前运行的活动。我目前有这个:

SELECT 
        *
FROM Activity_History AS A1
LEFT JOIN Activity_History AS A2
ON A2.Parent_Study_ID =
(
    SELECT TOP 1 Parent_Study_ID
    FROM Activity_History AS A3
    WHERE A3.Parent_Study_ID = A1.Parent_Study_ID 
          AND A3.Activity_Date < A1.Activity_Date
    ORDER BY Activity_Date DESC
)

这不起作用。正在发生的事情是它拉动查询的Activity_Date方没有任何效果,它只返回每行的降序日期顺序的第一个匹配的Activity_Date。我认为这种情况正在发生,因为在我的子查询中我在where中使用了Activity_Date,但这不在子查询中。

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

我假设您正在使用SQL Server?如果是这样,那么这应该使用ROW_NUMBER():

WITH CTE AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Parent_Study_Id ORDER BY Activity_Date ) RN
    FROM Activity_History
    )
SELECT * 
FROM CTE T1
    LEFT JOIN CTE T2 ON T1.RN = T2.RN+1 AND T1.Parent_Study_Id  = T2.Parent_Study_Id 

这是SQL Fiddle

答案 1 :(得分:0)

在SQLServer2005 +而不是LEFT JOIN中,您需要使用OUTER APPLY

SELECT *
FROM Activity_History AS A1 OUTER APPLY ( 
                                         SELECT TOP 1 Parent_Study_ID
                                         FROM Activity_History AS A2
                                         WHERE A2.Parent_Study_ID = A1.Parent_Study_ID 
                                           AND A2.Activity_Date < A1.Activity_Date
                                         ORDER BY A2.Activity_Date DESC
                                         ) o