T-SQL在一个查询之后获取特定日期之后的所有记录以及固定数字?

时间:2018-05-17 14:59:07

标签: sql-server tsql

样本数据表:

eventDate           eventText
------------------- ----------
2018-05-01 12:00:00 Some event
2018-05-02 13:00:00 Some event
2018-05-03 11:00:00 Some event
2018-05-04 11:00:00 Some event
2018-05-05 15:00:00 Some event
2018-05-06 14:00:00 Some event
2018-05-07 17:00:00 Some event
2018-05-08 16:00:00 Some event
2018-05-09 12:00:00 Some event
2018-05-10 11:00:00 Some event

我希望在特定日期之后检索所有记录,但ALSO在该日期之前记录达到特定最大记录数。

例如,假设我要求2018-05-05或之后的所有记录。

SELECT * FROM myTable WHERE eventDate >= '2018-05-05' ORDER BY eventDate

eventDate           eventText
------------------- ----------
2018-05-05 15:00:00 Some event
2018-05-06 14:00:00 Some event
2018-05-07 17:00:00 Some event
2018-05-08 16:00:00 Some event
2018-05-09 12:00:00 Some event
2018-05-10 11:00:00 Some event

但是现在我想在同一个查询结果中包含,最多两个记录在2018-05-05之前。所以:

SELECT * FROM myTable WHERE eventDate >= '2018-05-05' ORDER BY eventDate -- pseudocode "AND OR eventDate < 2018-05-05 WITH MAXIMUM EXTRA RECORDS 2

eventDate           eventText
------------------- ----------
2018-05-03 11:00:00 Some event
2018-05-04 11:00:00 Some event
2018-05-05 15:00:00 Some event
2018-05-06 14:00:00 Some event
2018-05-07 17:00:00 Some event
2018-05-08 16:00:00 Some event
2018-05-09 12:00:00 Some event
2018-05-10 11:00:00 Some event

最大记录是最大记录,因此如果没有足够的条目可以且不应该是错误:

SELECT * FROM myTable WHERE eventDate >= '2018-05-02' ORDER BY eventDate -- pseudocode "AND OR eventDate < 2018-05-02 WITH MAXIMUM EXTRA RECORDS 10

eventDate           eventText
------------------- ----------
2018-05-01 12:00:00 Some event
2018-05-02 13:00:00 Some event
2018-05-03 11:00:00 Some event
2018-05-04 11:00:00 Some event
2018-05-05 15:00:00 Some event
2018-05-06 14:00:00 Some event
2018-05-07 17:00:00 Some event
2018-05-08 16:00:00 Some event
2018-05-09 12:00:00 Some event
2018-05-10 11:00:00 Some event

如果没有记录符合初始条件,我也希望它有效;在该实例中只返回两个记录:

SELECT * FROM myTable WHERE eventDate >= '2018-06-30' ORDER BY eventDate -- pseudocode "AND OR eventDate < 2018-06-30 WITH MAXIMUM EXTRA RECORDS 2

eventDate           eventText
------------------- ----------
2018-05-09 12:00:00 Some event
2018-05-10 11:00:00 Some event

我可以在一个查询中执行此操作吗?

如果可能的话,最好还是希望在没有存储过程或功能的情况下这样做。

用例是一个API,它将返回“所有当前和未来记录的列表,包括当前时间之前的最近两个先前记录”

2 个答案:

答案 0 :(得分:3)

你似乎想要:

SELECT t.*
FROM ((SELECT t.*
       FROM myTable t
       WHERE eventDate >= '2018-05-05'
       ORDER BY eventDate
      ) UNION ALL
      (SELECT TOP (2) t.*
       FROM myTable t
       WHERE eventDate < '2018-05-05'
       ORDER BY eventDate DESC
      )
     ) t
ORDER BY eventDate;

答案 1 :(得分:0)

支票给戈登

但是可以更简单一些:

Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc