Hi,
I tried using the method described in this post:
Change Grafana Query Dynamically Based on User Inputs,
where the entire query is placed into a variable, but I haven’t been able to get it working. Could you help me further?
I’d like to dynamically switch between Query A and Query B in the same panel, based on the value of a variable.
Query A
Groups errors if they occur within 40 second of each other using the LAG
window function:
WITH cte1 AS (
SELECT
entity_id,
event_time,
code,
type,
description,
severity,
LAG(event_time) OVER (
PARTITION BY entity_id, code
ORDER BY event_time
) AS prev_event_time
FROM event_log_table
WHERE
severity IN ('critical', 'non_critical')
AND $__timeFilter(event_time)
AND entity_id = '$entity_id'
),
cte2 AS (
SELECT *,
CASE
WHEN prev_event_time IS NULL
OR event_time - prev_event_time > INTERVAL '40 seconds' THEN 1
ELSE 0
END AS new_group_flag
FROM cte1
),
cte3 AS (
SELECT *,
SUM(new_group_flag) OVER (
PARTITION BY entity_id, code
ORDER BY event_time
ROWS UNBOUNDED PRECEDING
) AS group_id
FROM cte2
)
SELECT
entity_id AS "Entity ID",
code AS "Code",
severity AS "Severity",
type AS "Type",
description AS "Description",
MIN(event_time) AS "First Occurrence",
MAX(event_time) AS "Last Occurrence",
EXTRACT(EPOCH FROM MIN(event_time)) * 1000 AS start_epoch_ms, -- time formatted for datalink
EXTRACT(EPOCH FROM MAX(event_time)) * 1000 AS end_epoch_ms, -- time formatted for datalink
MAX(event_time) - MIN(event_time) AS "Duration",
COUNT(*) AS "Number of Occurrences"
FROM cte3
GROUP BY
entity_id,
code,
type,
description,
severity,
group_id
ORDER BY "Last Occurrence" DESC;
Query B
Displays all errors filtered by variables and the dashboard’s time range:
SELECT
event_time AS "Error Timestamp",
entity_id AS "Entity ID",
code AS "Code",
type AS "Type",
description AS "Description",
severity AS "Severity"
FROM event_log_table
WHERE
entity_id IN ($entity_id)
AND code IN ($code)
AND severity IN ($severity)
AND $__timeFilter(event_time)
ORDER BY event_time DESC;
Any help on how to conditionally switch between these two queries based on a variable (e.g., mode = A or B
) would be greatly appreciated!