我有一个表dbo.counters,其中包含idx,idx_device,DateTime,Data1,Data2等列。
我需要从每个idx_device获得一个完整的行,该行最接近特定的DateTime,但不高于。
我已经得到了以下公式,但是这不会输出表中的所有列:
select max(DateTime), idx_device from dbo.counters
WHERE DateTime <= '02/04/12 23:59:59.995'
group by idx_device
猜测应该是小事,但我挂了......谢谢
答案 0 :(得分:2)
以下是使用Common Table Expressions的解决方案:
with cte as
(select
*,
row_number()
over (partition by idx_device order by DateTime desc) as rowno
from dbo.Counters
where DateTime < '2012-02-04')
select * from cte where rowno = 1
答案 1 :(得分:0)
以下内容可为您提供所需内容:
SELECT *
FROM dbo.Counters C
INNER JOIN
(SELECT idx_device,
MAX(DateTime) AS MaxDateTime
FROM dbo.Counters
WHERE DateTime < '20120205'
GROUP BY idx_device) AS MaxCounters
ON C.idx_device = MaxCounters.idx_device AND C.DateTIme = MaxCounters.MaxDateTime
您是对的,您需要按设备ID对记录进行分组以获取最长日期时间。一旦我们有了这些,我们就会加入到父表中,以检索具有相同设备ID 且具有该日期时间的记录。
请注意,如果同时有多个设备ID组合,您可能需要考虑使用DISTINCT。
答案 2 :(得分:0)
试试这个。
DECLARE @CompareDate Datetime
SET @CompareDate = '02/04/12 23:59:59.995'
;WITH c AS
(
SELECT *, rowrank = row_number() over(partition by idx_device order by DateTime desc)
FROM dbo.Counters
WHERE DateTime < @CompareDate
)
SELECT * FROM c WHERE rowrank = 1