SQL Server:查找表中的前5个元素,并在另一个表中找到前5个元素
问题描述:
我有一个SQL Server 2008 R2数据库,包含两个表:hystreal
和alarm
。SQL Server:查找表中的前5个元素,并在另一个表中找到前5个元素
在alarm
中,我有一个警告的字典和在某些条件下增加的事件。由于有一些线程有时间注册这些警报,因此在hystreal
中我注册了一个警报和线程注册它的时间戳。
因此,hystreal
看起来是这样的:
dataregvalue timestamp
--------------------------------------------------------------------------
ST8 err. cons. 1506352039
ST8 err. cons. 1506352049
ST8 err. cons. 1506352060
ST8 err. cons. 1506352070
ST8 err. cons. 1506352081
ST8 err. cons. 1506352091
ST8 err. cons. 1506352102
ST8 err. cons. 1506352112
ST8 err. cons. 1506352123
ST8 err. cons. 1506352133
ST8 err. cons. 1506352144
ST8 err. cons. 1506352154
ST8 err. cons. 1506352165
ST7 timeout 1506352448
ST7 timeout 1506352458
ST7 timeout 1506352469
ST7 timeout 1506352479
ST7 timeout 1506352490
ST7 timeout 1506352500
ST7 timeout 1506352511
ST7 timeout 1506352532
ST7 timeout 1506352543
ST7 timeout 1506352553
ST7 timeout 1506352564
ST7 timeout 1506352585
ST7 timeout 1506352595
ST7 timeout 1506353273
ST7 timeout 1506353283
ST7 timeout 1506353293
mac. stop 1506353367
mac. stop 1506353399
mac. stop 1506353420
mac. stop 1506353441
ST3 timeout 1506353714
ST3 timeout 1506353724
ST3 timeout 1506353735
ST3 timeout 1506353788
ST13 timeout 1506353809
ST13 timeout 1506353819
ST23 err. Z42 1506353893
ST23 err. Z42 1506353904
ST23 err. Z42 1506353914
ST23 err. Z42 1506353925
ST23 err. Z42 1506353935
ST23 err. Z42 1506353945
ST23 err. Z42 1506353956
ST23 err. Z42 1506353966
ST23 err. Z42 1506353977
ST23 err. Z42 1506353988
ST23 err. Z42 1506353998
ST23 err. Z42 1506354009
ST23 err. Z42 1506354019
ST23 err. Z42 1506354030
ST23 err. Z42 1506354041
ST7 timeout 1506354157
ST7 timeout 1506354167
ST7 timeout 1506354178
ST7 timeout 1506354188
ST7 timeout 1506354757
ST7 timeout 1506354767
ST7 timeout 1506354778
ST7 timeout 1506354789
一会儿,alarm
看起来是这样的:
communication occur
------------------------------------------------------------
ST8 err. cons. 75
ST7 timeout 15
mac. stop 43
ST3 timeout 7
ST13 timeout 33
ST23 err. Z42 1
我想找到前5 communication
(前5基于价值occur
)的alarms
,其所有相对时间戳为hystreal
。如何做到这一点?提前致谢!
N.B .: timestamp
的数量不是与价值occur
相关。可以有更多的timestamp
。
答
它可以是如此简单:
Select * from hystreal
where dataregvalue in
(
Select top 5 communication
from alarm
order by occur
)
我不理解你想要的输出。前5名基于什么标准?根据您的样本数据,您期望输出什么? –
我写到前5名应该是基于发生。 –
我知道你是基于发生的价值写下来的,但这是什么意思?最大的价值,最低的价值?仍然不明白你对输出的期望。 –