我有一个包含许多行的表,它们包含不同的日期,其中任何一个都将是当前时期。没有结束日期作为字段,否则我将比较从和之间的系统日期。我尝试过使用max函数,但仍会显示很多行。
数据按类型标识符分组,因此对于每种类型,都会有一个当前日期行。
考虑当前日期,获取当前行(单个)的最佳查询是什么?
以下是原始查询:
Select Group1,Group2,FromDate,FPFrom, FpTo FROM [DB].[dbo].[HGD] AS GD, [DB].[dbo].[HDT] AS TD WHERE GD.GRoup1 = TD.MainGroup
由于
答案 0 :(得分:0)
SELECT TOP 1 * FROM yourTable WHERE procStart <= getdate() ORDER BY procStart DESC
或类似
SELECT * FROM (SELECT TOP 1 * FROM yourTable row_number OVER(GROUP BY TypeId, Order By procStart DESC) RN WHERE procStart <= getdate()) DQ WHERE DQ.RN = 1
答案 1 :(得分:0)
请尽量准确。我想你看起来如下所示:
CREATE TABLE #temp(
SomeDate datetime,
SomeType int
)
INSERT #temp VALUES
('2016-07-20', 1),
('2016-07-23', 1),
('2016-07-27', 1),
('2016-07-30', 1),
('2016-01-25', 3),
('2016-01-31', 3),
('2016-02-21', 3),
('2016-07-23', 3),
('2016-09-30', 3)
WITH Numbered AS
(
SELECT SomeDate, SomeType, ROW_NUMBER() OVER (PARTITION BY SomeType ORDER BY SomeDate) RowNumber
FROM #temp
),
Ranges AS
(
SELECT T1.SomeDate StartPeriod, COALESCE(T2.SomeDate, DATEADD(year,1,GETDATE())) EndPeriod, T1.SomeType
FROM Numbered T1
LEFT JOIN Numbered T2 ON T1.RowNumber+1=T2.RowNumber AND T1.SomeType=T2.SomeType
)
SELECT * FROM Ranges
WHERE GETDATE() BETWEEN StartPeriod AND EndPeriod
ORDER BY SomeType
这会产生:
StartPeriod EndPeriod SomeType
2016-07-23 00:00:00.000 2016-07-27 00:00:00.000 1
2016-07-23 00:00:00.000 2016-09-30 00:00:00.000 3
答案 2 :(得分:0)
@Paweł Dyl
给了我一个想法,我在查询中添加了条件并获得了预期的结果。
ToDate字段不可用,因此我通过添加180天来创建一个字段。
AND GetDate() BETWEEN cast(FromDate as Date) AND DATEADD(DAY, 180,cast(FromDate as DATE))
再次感谢。