SQL Server - 循环遍历表并获取最新值和日期(性能问题)

时间:2017-04-14 05:23:36

标签: sql sql-server left-join

我的存储过程的目标是当我将 CABasicAnimation *endAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"]; endAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; [endAnimation setFromValue:[NSNumber numberWithFloat:1]]; [endAnimation setToValue:[NSNumber numberWithFloat:0.0]]; [endAnimation setBeginTime:AVCoreAnimationBeginTimeAtZero]; endAnimation.duration = 5; endAnimation.removedOnCompletion = NO; [alayer addAnimation:endAnimation forKey:nil]; 发送到存储过程时,我希望获取InstrumentID,最新值(ChannelDescription)和值那个时候)

我有3张桌子:datetime

仪器

  • InstrumentID
  • INSTRUMENTNAME

频道

  • ChannelID
  • InstrumentID
  • ChannelDescription
  • 缩放

基准

  • DatumId
  • 渠道ID
  • DATATIME
  • NumericValue

以下存储过程有效,但速度非常慢:

Instruments < Channels < Datum

2 个答案:

答案 0 :(得分:0)

以下代码可能更快,但假设特定渠道的数据时间不同:

SELECT 
    InstrumentId, c.ChannelId, d.DataTime,  
    CONVERT(DECIMAL(38, 4), (NumericValue / c.Scale)) AS NumericValue, 
    c.Diag, ChannelDescription
FROM
    (SELECT 
         channelid, MAX(datatime) datatime 
     FROM
         datum 
     GROUP BY 
         channelid) latest
JOIN
    channel c ON c.channelid = latest.channelid
JOIN
    datum d ON d.channelid = latest.channelid AND d.datatime = latest.datatime

答案 1 :(得分:0)

Select  
    chl.InstrumentId, chl.ChannelId, 
    tbl.maxdate,
    CONVERT(DECIMAL(38,4),(dt1.NumericValue/chl.Scale)) as NumericValue, 
    chl.ChannelDescription
from 
    channelid chl
inner join 
    (select 
         instrumentid, channelid, max(datatime) as maxdate 
     from 
         channel ch
     inner join 
         datum dt on dt.channel id = ch.channelid
     group by 
         instrumentid, channelid) tbl on tbl.instrumentid = chl.instrumentid 
                                      and chl.channelid = tbl.channelid
inner join 
    datum dt1 on dt1.datatime = tbl.maxdate and dt1.channelid = tbl.channelid
where 
    chl.instrumentid = @instrumentid