关于SQL查询,我是绿色的。非常绿色。
我有3张桌子。首先dbo.StringTable维护一个以字符串为数据的变量表。
DateAndTime TagIndex Val
2018-10-28 11:48:12.000 42 on load
2018-10-28 11:48:12.000 43 on load
2018-10-28 11:48:12.000 44 START
2018-10-28 11:48:12.000 45 on load
2018-10-28 11:48:12.000 46 on load
类似地,dbo.FloatTable具有以浮点数作为其值的标签;
DateAndTime TagIndex Val
2018-10-28 11:48:12.000 47 33.4
2018-10-28 11:48:12.000 48 42.3
2018-10-28 11:48:17.000 47 16.3
2018-10-28 11:48:17.000 48 18.0
2018-10-28 11:48:22.000 47 52.1
第三个(dbo.TabTable)在TagIndex和TagName之间具有静态映射
TagName TagIndex
gtg_evnt\4 45
gtg_evnt\5 46
plc\system\capacity\1 47
plc\system\load\1 48
plc\system\req_load\1 49
每5秒钟将数据记录到FloatTable和StringTable中,但是当发生“事件”时,它将触发额外的数据写入到这两个表中。
我需要做的是
这种查询超出了我的能力。我花了3个小时来阅读SQL命令,并取得了一些进展,但是当我确定你们中的一个人会在几分钟之内解决这个问题时,这可能会花费我数小时/每天的时间。
基于以下答案,我已经完成了以下工作。像这样将其隔开之后,我便完成了每个部分的工作-更加有意义。
我已根据最终查询对其进行了更新,并添加了一些评论,希望对您有所帮助。
SELECT
B.DateandTime
,D.TagName
,B.Val
/** First, make a derived table 'A' with all the GTG Events in the past 1 day **/
FROM
( SELECT DateAndTime
,TagIndex
,Val
FROM [FTViewDatalog].[dbo].StringTable
WHERE val in ('Start','Stop') AND
DateAndTime >= GETDATE()-1
) A
/** The UNION creates a big table with StringTable and FloatTable merged together **/
/** The INNER JOIN then takes each of the DateAndTime from A, and gets the events from 10 seconds before and 10 seconds after **/
INNER JOIN
( SELECT DateAndTime
,TagIndex
,Val
FROM [FTViewDatalog].[dbo].StringTable
UNION
SELECT DateAndTime
,TagIndex
,Cast(Val AS varchar(50)) AS Val
FROM [FTViewDatalog].[dbo].FloatTable
) B
ON B.DateAndTime BETWEEN DATEADD(ss,-10,A.DateAndTime ) AND DATEADD(ss,10,A.DateAndTime )
/** Use an INNER JOIN to 'convert' the TagIndex into a TagName **/
INNER JOIN [FTViewDatalog].[dbo].TagTable D ON D.TagIndex=B.TagIndex
/** Use this if you want to filter out specific tags **/
/** WHERE D.TagName IN ('plc\system\req_load\1','plc\system\load\1', 'plc\system\capacity\1') OR D.TagName LIKE 'gtg_evnt\[1-7]' **/
/** Sort by date **/
ORDER BY B.DateAndTime ASC
答案 0 :(得分:0)
这可以帮助您随时让我知道任何问题,
Select C.TagName as OriginalEventName,A.DateandTime as OriginalEventTimeStamp,D.TagName as ParallelEventName,B.DateandTime as ParallelEventTimeStamp
from
(Select Cast(DateAndTime as datetime) as DateAndTime,Tagindex,cast(Val as Varchar(50)) as Val from StringTable
where val in ('Start','Stop'))A
inner join Tabtable C on C.Tagindex=A.TagIndex
Inner join
(Select Cast(DateAndTime as datetime) as DateAndTime,Tagindex,cast(Val as Varchar(50)) as Val from StringTable
Union
Select cast(DateAndTime as datetime) as DateAndTime,Tagindex,cast(Val as Varchar(50)) as Val FloatTable)B
on B.DateAndTime between DATEADD(ss,-10,A.DateAndTime ) and DATEADD(ss,10,A.DateAndTime )
inner join Tabtable D on D.Tagindex=B.TagIndex