R - hydropoc/website Wiki

USE HydroPoC;
DROP PROCEDURE IF EXISTS getSensorData;
GO
CREATE PROCEDURE getSensorData @time BIGINT, @interval SMALLINT
    AS
        BEGIN
            DECLARE @start1 BIGINT = CAST(DATEDIFF(s, '1970-01-01 00:00:00.000', CAST(SYSDATETIME() AS NVARCHAR(200))) AS BIGINT);
            DECLARE @end1 BIGINT = @start1 - @time;
            EXECUTE sp_execute_external_script @language = N'R'
                , @script = N'OutputDataSet <- InputDataSet;
                    print(mean(c(OutputDataSet$temperature_water)));
                    print(end); print(interval);'
                , @input_data_1 = N'SELECT *
                    FROM
                        (
                            SELECT *, ROW_NUMBER() OVER (ORDER BY timestamp) AS rownum
                            FROM sensordata
                            WHERE timestamp BETWEEN @end AND @start
                        )
                    AS t
                    WHERE t.rownum % @interval = 0
                    ORDER BY t.timestamp;'
                , @params = N'@start BIGINT OUTPUT, @end BIGINT OUTPUT, @interval SMALLINT OUTPUT'
                , @start = @start1
                , @end = @end1
                , @interval = @interval
                WITH RESULT SETS(
                    (
                        [ID] INT NOT NULL,
                        [temperature_water] DECIMAL NOT NULL,
                        [temperature_air] DECIMAL NOT NULL,
                        [humidity] DECIMAL NOT NULL,
                        [co2_level] DECIMAL NOT NULL,
                        [ph_value] DECIMAL NOT NULL,
                        [ec_value] DECIMAL NOT NULL,
                        [swimmer_1] INT NOT NULL,
                        [swimmer_2] INT NOT NULL,
                        [swimmer_3] INT NOT NULL,
                        [timestamp] BIGINT NOT NULL,
                        [rownum] INT NOT NULL
                    )
                );
        END;
        GO
EXEC getSensorData @time = 100, @interval = 30;
`