复杂的SQL我不想在存储过程中转换

时间:2010-10-15 17:47:00

标签: c# sql sql-server sql-server-2005

我希望得到您的帮助,以便了解是否可以在不需要存储过程的情况下实现所需的查询。我会尽力解释自己。

我有类似的结构:

PK / FK / DateTime / Value
1  / 68 / 10:30    / 60.5
2  / 68 / 09:30    / 10.5
3  / 61 / 05:30    / 01.0
4  / 58 / 04:30    / 22.2
5  / 58 / 01:00    / 15.0

这些行定义了由外键(FK)描述的某种事件。我想要实现的是获取一组事件(FK)的两个最新行。

某种

SELECT TOP 2 * 
FROM TABLE 
WHERE FK IN (68,58) 
ORDER BY DATETIME DESC

,但在IN子句中获取每行FK的两行。

在自然语言中,所需的操作是在IN子句中迭代FK并生成

SELECT TOP 2 * 
FROM TABLE 
ORDER BY DATETIME DESC.

我想知道是否可以在一个SQL中表达它。

非常感谢,

4 个答案:

答案 0 :(得分:4)

一个选项

SELECT
    B.*
FROM
    (SELECT DISTINCT FK FROM MyTable) A
    CROSS APPLY
    (
    SELECT TOP 2 * 
    FROM TABLE T
    WHERE T.FK = A.FK
    ORDER BY DATETIME DESC
    ) B

或者

;WITH CTE AS
(
   SELECT *
      ROW_NUMBER() OVER (PARTITION BY FK ORDER BY DATETIME DESC) AS RowNum
   FROM
      Table
)
SELECT * FROM CTE WHERE RowNum <= 2

答案 1 :(得分:3)

    SELECT d.*
    FROM(
         SELECT DISTINCT FK FROM YourTable
         ) AS y
    OUTER APPLY(
    SELECT TOP 2 * 
      FROM YourTable AS y1
        WHERE y1.FK = y.FK
        ORDER BY DATETIME DESC
    ) AS d

答案 2 :(得分:1)

您可以随时使用联合:

SELECT TOP 2 * FROM TABLE WHERE FK = 68 ORDER BY DATETIME DESC
UNION
SELECT TOP 2 * FROM TABLE WHERE FK = 58 ORDER BY DATETIME DESC

答案 3 :(得分:1)

SELECT D.*
FROM ( 
   SELECT t.*
      ,  ROW_NUMBER = ROW_NUMBER() OVER (
              PARTITION BY FK 
              ORDER BY DateTime DESC
         ) 
   FROM Table AS t
) AS D
WHERE D.ROW_NUMBER <= 2

或用户RowNumber