# 一些sql语句

duration_hour_one_equip = """
WITH time_data AS (
	SELECT
		TO_CHAR( G.TIMEX, 'YYYY-MM-DD HH24:MI:SS' ) AS TIMEX 
	FROM
		generate_series ( '{start_time}' :: TIMESTAMP, '{end_time}' :: TIMESTAMP, '1 minute' ) G ( TIMEX ) 
	),
	ev_data AS (
	SELECT
		TO_CHAR( time_bucket ( '1 minute', TIMEX ) AT TIME ZONE'Asia/Shanghai', 'YYYY-MM-DD HH24:MI:SS' ) AS timex,
		MAX ( running_state ) AS running_state,
        AVG ( tsp ) AS avg_tsp 
	FROM
		enp_envdata envdata 
	WHERE
		envdata.equipment_id = '{equipment_id}' 
		AND envdata.TIMEX AT TIME ZONE'Asia/Shanghai' >= '{start_time}' 
		AND envdata.TIMEX AT TIME ZONE'Asia/Shanghai' <= '{end_time}'
	GROUP BY
		time_bucket ( '1 minute', TIMEX ) AT TIME ZONE'Asia/Shanghai' 
	ORDER BY
		timex 
	),
	state_d AS (
	SELECT 
    avg_tsp,
	COALESCE
		( ed.running_state, 50 ) AS running_state 
	FROM
		time_data td
		LEFT JOIN ev_data ed ON ed.timex = td.timex 
	ORDER BY
		td.timex 
	) SELECT
    ROUND( cast(AVG ( avg_tsp ) as numeric), 4) AS avg_tsp,
	ROUND( SUM ( CASE WHEN running_state = 10 THEN 1 ELSE 0 END ) / 60.0, 2 ) AS duration_run,
	ROUND( SUM ( CASE WHEN running_state = 30 THEN 1 ELSE 0 END ) / 60.0, 2 ) AS duration_stop,
	ROUND( SUM ( CASE WHEN running_state = 50 THEN 1 ELSE 0 END ) / 60.0, 2 ) AS duration_offline 
FROM
	state_d;
"""
