我有一个如下所示的数据库表:
现在。这是 DetectorID 1541 的状态历史指示器。
我只想在我的网站上显示 1 行。为此,我执行了以下查询。
[Query]
public IQueryable<ScannerStatusHistory> GetScannerStatusHistoryy(int detectorID)
{
return ObjectContext.ScannerStatusHistories.Where(t => t.DetectorID == detectorID).OrderByDescending(d => d.TimeStamp).Take(1); ;
}
那么它的作用是,它获取最新的行(基于时间戳)并显示它。
这将给我 ScannerStatusHistoryID 61
的结果。
但是,我想要的是最后一次更改值的行。
如您在 ScannerStatusHistoryID 54
中所见,RC3
的值为 4
。然后在 ScannerStatusHistoryID 57
上,它变回 3
。
从那以后,值(value)观没有改变。
那么我想要的是获取 ScannerStatusHistoryID 57
的查询。直到值再次改变,然后我希望它捕获第一个。
我如何实现这一点?我正在考虑计算与上次查询匹配的结果。但是,在此示例中,它将返回 7 个结果(因为前 4 个与后 3 个相同)。所以它不会给你正确的结果。
最佳答案
您可以像这样编写查询来实现它:
//return ObjectContext.ScannerStatusHistories.Where(t => t.DetectorID == detectorID).OrderByDescending(d => d.TimeStamp).Take(1);
var lastRow = ObjectContext.ScannerStatusHistories.Where(t => t.DetectorID == detectorID).OrderByDescending(d => d.TimeStamp).FirstOrDefault();
//Get last changed row
if (lastRow != null)
{
var lastChangeRow = ObjectContext.ScannerStatusHistories
.Where(t => t.DetectorID == detectorID
&& (t.HBD1 != lastRow.HBD1 || t.HBD2 != lastRow.HBD2 || t.HWD1 != lastRow.HWD1 || t.HWD2 != lastRow.HWD2 || t.RC1 != lastRow.RC1 || t.RC2 != lastRow.RC2 || t.RC3 != lastRow.RC3 || t.RC4 != lastRow.RC4))
.OrderByDescending(d => d.TimeStamp)
.FirstOrDefault();
//Return next row
if (lastChangeRow != null)
{
return ObjectContext.ScannerStatusHistories
.Where(x => lastChangeRow.TimeStamp < x.TimeStamp
&& x.DetectorID == detectorID)
.OrderBy(d => d.TimeStamp)
.Take(1);
}
}
return ObjectContext.ScannerStatusHistories.Where(t => t.DetectorID == detectorID).OrderBy(d => d.TimeStamp).Take(1);
但也许如果没有任何更改则不添加行会更好?
关于自值更改后 C# 查询首先选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41850085/