SAMPLE QUERY

SAMPLE QUERY
mail@pastecode.io avatar
unknown
sql
2 years ago
717 B
6
Indexable

WITH AS FORMATTED_EVENTS AS (
	SELECT
		DATE(DATETIME) AS EVENT_DATE,
		CLIENTID,
		BILLINGCODE,
		EVENTTYPE,
		COUNT(*) AS TOTAL_COUNT,
		SUM(EVENT_HR) AS SUM_OF_COUNT,
		COUNT(DISTINCT CLIENTID) AS UNIQUE_CLIENTID
	FROM
		EVENT_TABLE
	GROUP BY 1, 2, 3, 4
)

SELECT
	B.EVENT_DATE,
	A.*,
	CASE
		WHEN A.METRIC_COLUMN1 = 'COUNT' AND A.METRIC_COLUMN2 = 'DISTINCT' THEN B.UNIQUE_CLIENTID
		WHEN A.METRIC_COLUMN1 = 'COUNT' THEN B.TOTAL_COUNT
		WHEN A.METRIC_COLUMN1 = 'SUM' THEN B.TOTAL_COUNT
		ELSE 0
	END AS OUTPUT
FROM 
	METRIC_TABLE AS A
	INNER JOIN FORMATTED_EVENTS AS B
		ON B.CLIENTID = A.CLIENT_ID
			AND B.BILLINGCODE = A.BILLING_CODE
				AND B.EVENTTYPE = A.APPLICATION_TYPE
ORDER BY 1 DESC -- OPTIONAL SORTING