如何关联2个历史表之间的记录?

时间:2013-03-01 22:06:32

标签: sql sql-server-2008 tsql

我有5张表(为这个问题设计和简化):

Device
---------------
DeviceID - INT IDENTITY - PRIMARY KEY
DeviceGUID - UNIQUEIDENTIFIER - UNIQUE CLUSTERED (used for lookups)
OtherInfo


Device_State
---------------
DeviceStateID - INT IDENTITY - PRIMARY KEY
DeviceID - INT - FOREIGN KEY - UNIQUE CLUSTERED (used for lookups)
Pump1 - TINYINT
Pump2 - TINYINT
Pump3 - TINYINT
Pump4 - TINYINT
Pump5 - TINYINT
Heater1 - TINYINT
Heater2 - TINYINT
Lights - BIT
TimeStamp - SMALLDATETIME

Device_State_History
---------------
DeviceStateHistoryID - INT IDENTITY - PRIMARY KEY
DeviceStateID - INT - FOREIGN KEY - NONCLUSTERED INDEX (used for lookups)
Pump1 - TINYINT
Pump2 - TINYINT
Pump3 - TINYINT
Pump4 - TINYINT
Pump5 - TINYINT
Heater1 - TINYINT
Heater2 - TINYINT
Lights - BIT
TimeStamp - SMALLDATETIME


Peripheral_State
----------------
PeripheralStateID - INT IDENTITY - PRIMARY KEY
DeviceID - INT - FOREIGN KEY - UNIQUE CLUSTERED (used for lookups)
Pump1 - TINYINT
Pump2 - TINYINT
PH - SMALLINT
ORP - SMALLINT
ELECTRODEID - TINYINT
ELECTRODEPOLARITY - TINYINT
TimeStamp - SMALLDATETIME


Peripheral_State_History
----------------
PeripheralStateHistoryID - INT IDENTITY - PRIMARY KEY
PeripheralStateID - INT - FOREIGN KEY - NONCLUSTERED INDEX (used for lookups)
Pump1 - TINYINT
Pump2 - TINYINT
PH - SMALLINT
ORP - SMALLINT
ELECTRODEID - TINYINT
ELECTRODEPOLARITY - TINYINT
TimeStamp - SMALLDATETIME

情况如下:

我在Device_State_History表中有~380万条记录,我在Peripheral_State_History表中有~100K条记录。

我想编写一个查询,在给定日期时间内为给定的DeviceGUID选择所有Peripheral_State_history和Device_State_History。我想得到像这样的记录:

Select 
 Peripheral_State_History.PH,
 Peripheral_State_History.ORP,
 ( 
 if(Device_State_History.Pump1 == 1 ||
    Device_State_History.Pump2 == 1 ||
    Device_State_History.Pump3 == 1 ||
    Device_State_History.Pump4 == 1 || 
    Device_State_History.Pump5 == 1
    ) 
    { 1 }
    else 
    { 0 }
  ) AS PumpsOn, 
    TimeStamp 
FROM CombinedData

此外,Device_State_History和Peripheral_State_History之间的TimeStamps并不总是相同。我的意思是,Device_State_History表中1个设备的记录时间戳可能是这样的:

Mar-1-2013 12:31
Mar-1-2013 12:33
Mar-1-2013 12:36
Mar-1-2013 12:38
Mar-1-2013 12:41

然后Peripheral_State_History表中会有记录:

Mar-1-2013 12:29
Mar-1-2013 12:33
Mar-1-2013 12:34
Mar-1-2013 12:38
Mar-1-2013 12:39
Mar-1-2013 12:41

如您所见,时间戳并不总是重叠。

我一直在阅读并尝试编写存储过程来执行此操作,但是,这超出了我的SQL能力,指导和示例非常感谢。感谢信。

编辑:

以下是我为从Peripheral_State_History表中获取数据而编写的存储过程。它不包括我想从Device_State_History表中获取的泵数据。

有几点要注意:我每张时间戳只能获得1条记录,因为有一些时间戳有多条记录。此存储过程从State表中获取当前记录,以及从历史表中删除所有记录。

USE my_db
GO
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'SP_Select_Stuff') 
DROP PROCEDURE 'SP_Select_Stuff') 
GO
CREATE PROCEDURE 'SP_Select_Stuff') 
( 
     @DeviceGUID uniqueidentifier
) 
AS
DECLARE @RetCode INT
;WITH combined AS
(
    SELECT 
    ROW_NUMBER() OVER 
   (PARTITION BY [TimeStamp] ORDER BY [TimeStamp]) as num, ORP, PH, [TimeStamp] 
    FROM Peripheral_State
    INNER JOIN Device
        ON Peripheral_State.DeviceID = Device.DeviceID
        WHERE Device.DeviceGUID = @DeviceGUID 
    UNION ALL
    SELECT
    ROW_NUMBER() OVER 
   (PARTITION BY [TimeStamp] ORDER BY [TimeStamp]) as num, ORP, PH, [TimeStamp]
    FROM Peripheral_State_History
    INNER JOIN Device
        ON Peripheral_State.DeviceID = Device.DeviceID
        WHERE Device.DeviceGUID = @DeviceGUID 

)
SELECT ORP, PH, [TimeStamp]
FROM combined
WHERE ORP > 0
AND PH > 0
AND combined.num = 1
ORDER BY [TimeStamp] ASC

IF @@ERROR <> 0
   BEGIN
        SET @RetCode = 5
        RETURN @RetCode
   END
ELSE
    BEGIN
        SET @RetCode = 0
        RETURN @RetCode
    END
GO

编辑:

这是我想出的。

USE my_db
--"combined" gets all of the data. 
--A row from the peripheral history will look like: ORP-Value, PH-Value, Current-Value, NULL, TimeStamp.
--A row from the device history will look like: NULL, NULL, NULL, PumpsOn-Value, TimeStamp
-- I also get a num for filtering 1 TimeStamp per minute. My TimeStamps are accurate to the minute, so if one minute has 30 records, I will use the first record.
;WITH combined AS
(   
    SELECT  
    ROW_NUMBER() OVER 
   (PARTITION BY ph.[TimeStamp] ORDER BY ph.[TimeStamp]) as num, ph.ORP, ph.PH, ph.[Current], NULL as PumpsOn, ph.[TimeStamp] 
    FROM Device as d

    LEFT JOIN Peripheral_State as ps
    ON ps.DeviceID = d.DeviceID

        LEFT JOIN Peripheral_State_History as ph
        ON ph.DeviceID = d.DeviceID

        WHERE d.DeviceGUID = @DeviceGUID
        AND ph.TimeStamp BETWEEN '2013-03-02 00:00:00' AND GETDATE() 

    UNION ALL   

    SELECT
    ROW_NUMBER() OVER 
   (PARTITION BY dh.[TimeStamp] ORDER BY dh.[TimeStamp]) as num, NULL as ORP, NULL as PH, NULL as [Current], IsNull(COALESCE(dh.Pump1, dh.Pump2, dh.Pump3, dh.Pump4, dh.Pump5),0) as PumpsOn, dh.[TimeStamp]
    FROM Device as d

    LEFT JOIN Device_State as ds
    ON ds.DeviceID = d.DeviceID

       LEFT JOIN Device_State_History as dh
       ON dh.DeviceID = d.DeviceID

        WHERE d.DeviceGUID = @DeviceGUID
        AND ph.TimeStamp BETWEEN '2013-03-02 00:00:00' AND GETDATE()            
),
--"FilteredAndAddID" gets a record set that has an ID added to the row. This is required for the 3rd step.
--It also filters the data so that records with 0 orp/ph are omitted.
FilteredAndAddID AS
(
    SELECT 
        ROW_NUMBER() OVER (ORDER BY [TimeStamp]) as ID,
        ORP,
        PH,
        [Current],
        PumpsOn,
        [TimeStamp]
    FROM combined
    WHERE 
    (ORP is NULL OR ORP > 0) AND (PH is NULL OR PH > 0)
    AND combined.num = 1
),
--"filled" is used to fill the "FilteredAddID" record set NULLS with the previous row that has a value instead of NULL.
filled AS
(
    SELECT  Curr.ID,
            ISNULL(Curr.ORP, (SELECT TOP 1 ORP FROM FilteredAddID WHERE ID < Curr.ID AND ORP IS NOT NULL ORDER BY ID)) ORP,
            ISNULL(Curr.PH, (SELECT TOP 1 PH FROM FilteredAddID WHERE ID < Curr.ID AND PH IS NOT NULL ORDER BY ID)) PH,
            ISNULL(Curr.[Current], (SELECT TOP 1 [Current] FROM FilteredAddID WHERE ID < Curr.ID AND [Current] IS NOT NULL ORDER BY ID)) [Current],
            ISNULL(Curr.PumpsOn, (SELECT TOP 1 PumpsOn FROM FilteredAddID WHERE ID < Curr.ID AND PumpsOn IS NOT NULL ORDER BY ID)) PumpsOn, 
            Curr.[TimeStamp]
    FROM    FilteredAddID Curr
)
SELECT ID, ORP, PH, [Current], PumpsOn, [TimeStamp]
FROM filled
ORDER BY [TimeStamp] ASC

前两个查询“combined”和“FilterAndAddID”以毫秒为单位执行,但“已填充”查询大约需要6分钟来填充~1700条记录中的空值。

反正有加速吗?

我是以正确的方式接近这个吗?

理想情况下,我需要在几秒钟内运行。

1 个答案:

答案 0 :(得分:1)

此查询运行多长时间?

;with combined as
(
select
   psh.PH, psh.ORP, psh.TimeStamp, 
   max(dsh.TimeStamp) as Device_Stamp
from Peripheral_State_History psh
  join Peripheral_State ps on ps.PeripheralStateID = psh.PeripheralStateID 
  join Device d on d.DeviceID = ps.DeviceID
  left join Device_State ds on ds.DeviceID = d.DeviceID
  left join Device_State_History dsh on dsh.DeviceStateID = ds.DeviceStateID 
    and dsh.TimeStamp <= psh.TimeStamp
where d.DeviceGUID = @DeviceGUID
  and psh.TimeStamp between @date1 and @date2
group by psh.PH, psh.ORP, psh.TimeStamp
)
select 
  c.PH, c.ORP, c.TimeStamp, 
  case 
    when dsh.Pump1 = 1 and dsh.Pump2 = 1 and dsh.Pump3 = 1 
      and dsh.Pump4 = 1 and dsh.Pump5 = 1
    then 1 else 0 end as PumpsOn
from combined c
  left join Device_State_History dsh on dsh.TimeStamp = c.Device_Stamp
  left join Device_State ds on ds.DeviceStateID = dsh.DeviceStateID
  left join Device d on ds.DeviceID = d.DeviceID
where d.DeviceGUID = @DeviceGUID

修改

解决Device_State_History中具有相同时间戳的多个记录的问题。

如果您有更大的DeviceStateHistoryID总是大于或等于时间戳,那么您可以尝试此查询。它选择一条带有最大DeviceStateHistoryID的记录,其中记录在Device_State_History中具有相同的时间戳

;with combined as
(
select
   psh.PH, psh.ORP, psh.TimeStamp, 
   max(dsh.DeviceStateHistoryID) as DeviceStateHistoryID
from Peripheral_State_History psh
  join Peripheral_State ps on ps.PeripheralStateID = psh.PeripheralStateID 
  join Device d on d.DeviceID = ps.DeviceID
  left join Device_State ds on ds.DeviceID = d.DeviceID
  left join Device_State_History dsh on dsh.DeviceStateID = ds.DeviceStateID 
    and dsh.TimeStamp <= psh.TimeStamp
where d.DeviceGUID = @DeviceGUID
  and psh.TimeStamp between @date1 and @date2
group by psh.PH, psh.ORP, psh.TimeStamp
)
select 
  c.PH, c.ORP, c.TimeStamp, 
  case 
    when dsh.Pump1 = 1 and dsh.Pump2 = 1 and dsh.Pump3 = 1 
      and dsh.Pump4 = 1 and dsh.Pump5 = 1
    then 1 else 0 end as PumpsOn
from combined c
  left join Device_State_History dsh on dsh.DeviceStateHistoryID = c.DeviceStateHistoryID
  left join Device_State ds on ds.DeviceStateID = dsh.DeviceStateID
  left join Device d on ds.DeviceID = d.DeviceID
where d.DeviceGUID = @DeviceGUID