2014-02-26 16 views
0

我可以在PHP中解決以下問題,但我不知道它是否可以在SQLite中完成。如何在sqlite中集成電流

簡化版本看起來像這樣:我有一個簡單的電路。我可以獨立地打開和關閉紅色,綠色和藍色的燈。我記錄安培爲每個光以秒的定時和電流在一個表中,如下所示:

| Lamp | On | Off | Current | 
|-------|----|:---:|--------:| 
| red | 2 | 14 |  3 | 
| green | 5 | 8 |  8 | 
| blue | 6 | 10 |  2 | 

正如你可以看到,它們重疊。如果我想正確地整合電流(計算能量消耗),我必須將這個表格轉換成一個新的表格,從而增加電流。我得到下面的表(手動)與適應的時間:

| T1 | T2 | Sum(Current) |  Comment | 
|:--:|:--:|-------------:|:--------------:| 
| 2 | 5 |   3 |  red  | 
| 5 | 6 |   11 | red+green | 
| 6 | 8 |   13 | red+green+blue | 
| 8 | 10 |   5 | red+blue | 
| 10 | 14 |   3 |  red  | 

任何想法,如果sqlite可以做到這一點?也許通過創建臨時表?

回答

1

這是相當複雜的,但我可以用一對夫婦的意見,做到這一點:

create table elec (lamp char(10),on_tm int,off_tm int,current int); 

insert into elec values 
('red',2,14,3), 
('green',5,8,8), 
('blue',6,10,2); 

create view all_tms as 
select distinct on_tm 
    from elec 
union 
select distinct off_tm 
    from elec; 

create view all_periods as 
select t1.on_tm, 
     (select min(t2.on_tm) 
      from all_tms t2 
     where t2.on_tm > t1.on_tm) off_tm 
    from all_tms t1 

select 
    all_periods.on_tm, 
    all_periods.off_tm, 
    sum(case when elec.on_tm <= all_periods.on_tm 
      and elec.off_tm >= all_periods.off_tm 
     then elec.current 
     else 0 
     end) total_current, 
    group_concat(case when elec.on_tm <= all_periods.on_tm 
        and elec.off_tm >= all_periods.off_tm 
    then elec.lamp 
    end) lamps 
from 
    all_periods, 
    elec 
group by 
    all_periods.on_tm, 
    all_periods.off_tm 

的意見,結合所有的啓動/停止時間爲不同的塊,你在你的輸出有(2- 5,5-6等)。

最終的SELECT根據每個時間塊評估原始表中的每一行。如果指示燈亮起(開始時間在評估時間開始之前,並且停止時間在評估時間結束之後),則對其電流進行計數。

1

此處假定爲sufficiently recent SQLite version;與早期版本,你將不得不用臨時代替common table expressionsviews

WITH all_times(T) 
AS (SELECT "On" FROM MyTable 
    UNION 
    SELECT Off FROM MyTable), 
intervals(T1, T2) 
AS (SELECT T, 
      (SELECT min(T) 
      FROM all_times AS next_time 
      WHERE next_time.T > all_times.T) AS T2 
    FROM all_times 
    WHERE T2 IS NOT NULL) 
SELECT T1, 
     T2, 
     (SELECT sum(Current) 
     FROM MyTable 
     WHERE T1 >= "On" AND T2 <= Off) AS Current_Sum, 
     (SELECT group_concat(lamp, '+') 
     FROM MyTable 
     WHERE T1 >= "On" AND T2 <= Off) AS Comment 
FROM intervals 
ORDER BY T1 
+0

看起來緊湊和優雅。由於sqlite版本,我無法測試它。 –