I have some data in SQLite files, and want to manipulate it from C#.
The data includes three columns, Time
, Temperature
and Power
. And I want to find the groups of records which have a Temperature
higher than 30, and last more than 3 minutes, and calculate the mean of power of each group (continuous time range).
Select continuous ranges from table
How to Select continuous date in sql
I find two answers above, but can't reach the answer of mine.
It can be get the results directly with a SQL string (for SQLiteDataAdapter). or select all data and manipulate it with c# (datatable.Select,Computer, or LINQ).
| No | Time | Temp | Power |
| ---- | ----------------- | ---- | ----- |
| 1 | 2019-11-4 0:00:00 | 25 | 1200 |
| 2 | 2019-11-4 0:01:10 | 30 | 1000 |
| 3 | 2019-11-4 0:02:20 | 31 | 680 |
| 4 | 2019-11-4 0:03:30 | 34 | 960 |
| 5 | 2019-11-4 0:04:40 | 29 | 800 |
| 6 | 2019-11-4 0:05:50 | 31 | 600 |
| 7 | 2019-11-4 0:07:00 | 32 | 400 |
| 8 | 2019-11-4 0:08:10 | 33 | 900 |
| 9 | 2019-11-4 0:09:20 | 34 | 1000 |
| 10 | 2019-11-4 0:10:30 | 39 | 200 |
| 11 | 2019-11-4 0:11:40 | 24 | 350 |
Expected results: select the continuous records when Temp
more than 30 and continuous time more than 3 minutes as a group, and calculate the mean of Power
.
One group in the example table including No from 6 to 10. And the mean is 620.
Thanks to all.The codes used in my works:
string sql = "WITH CTE AS (" +
"SELECT(Temp > 30) AS tempgt30,Time, Power," +
"ROW_NUMBER() OVER(ORDER BY No) rn," +
"ROW_NUMBER() OVER(PARTITION BY(Temp > 30) ORDER BY No) rn2" +
" FROM data" +
")" +
" SELECT MIN(rn)AS minrow,MAX(rn) as maxrow," +
"strftime('%s', MAX(Time)) - strftime('%s', MIN(Time)) AS duration," +
"AVG(Power) AS mean" +
" FROM CTE" +
" WHERE tempgt30" +
" GROUP BY(rn2 - rn)" +
" HAVING duration > 180;";
con.Open();
if (con.State == ConnectionState.Open)
{
using (SQLiteDataAdapter dataAdapter = new SQLiteDataAdapter(sql, con))
{
dataAdapter.Fill(datatable);
con.Close();
}
}