Sql of note/Pivoting in sql: Difference between revisions

From Federal Burro of Information
Jump to navigationJump to search
No edit summary
No edit summary
Line 1: Line 1:
On this case I'm using SQLite, but any ANSI sql will work.
the schema:
<pre>
sqlite> .schema
CREATE TABLE thedata
            (collecttime int, sensor1 int, sensor2 int);
sqlite>
</pre>


thdata:
thdata:

Revision as of 21:41, 7 November 2018

On this case I'm using SQLite, but any ANSI sql will work.

the schema:

sqlite> .schema
CREATE TABLE thedata
             (collecttime int, sensor1 int, sensor2 int);
sqlite> 

thdata:

sqlite> select * from thedata limit 10;
collecttime|sensor1|sensor2
1525694702|685|255
1525695002|694|262
1525695302|706|267
1525695602|706|269
1525695902|700|267
1525696202|700|266
1525696502|697|264
1525696802|695|261
1525697102|694|259
1525697402|698|261

How many record for each hour ?

SELECT count(*), hour
from (
    SELECT
    date ( datetime(collecttime, 'unixepoch', 'localtime') ) as day,
    strftime('%H', datetime(collecttime, 'unixepoch', 'localtime') ) as hour,
    avg(sensor1) as theavg
    from thedata
    group by day , hour
)
group by hour;


Intermediate step:

select day,
 CASE WHEN hour == '21' THEN theavg ELSE 0 END AS twentyone
 FROM (
    SELECT
    date ( datetime(collecttime, 'unixepoch', 'localtime') ) as day,
    strftime('%H', datetime(collecttime, 'unixepoch', 'localtime') ) as hour,
    avg(sensor1) as theavg
    from thedata
    where 
      date ( datetime(collecttime, 'unixepoch', 'localtime') ) == '2018-10-25'
    group by day, hour
    )