LAG
. का उपयोग करने पर विचार करें विंडो फ़ंक्शन और कंडीशनल एग्रीगेशन कई सीटीई और सेल्फ़-जॉइन के ज़रिए जुड़ते हैं:
WITH sub AS (
SELECT "user"
, "type"
, "date"
, CASE
WHEN LAG("type") OVER(PARTITION BY "user" ORDER BY "date") = "type"
THEN 0
ELSE 1
END "shift"
FROM myTable
), agg AS (
SELECT "user"
, MIN(CASE WHEN shift = 1 THEN "date" END) AS min_shift_dt
, MAX(CASE WHEN shift = 1 THEN "date" END) AS max_shift_dt
FROM sub
GROUP BY "user"
)
SELECT agg."user"
, s1."type" AS first_type
, s1."date" AS first_type_initial_date
, s2."type" AS last_type
, s2."date" AS last_type_initial_date
FROM agg
INNER JOIN sub AS s1
ON agg."user" = s1."user"
AND agg.min_shift_dt = s1."date"
INNER JOIN sub AS s2
ON agg."user" = s2."user"
AND agg.max_shift_dt = s2."date"
उपयोगकर्ता | <थ>प्रथम_प्रकार <थ>पहली_प्रकार_प्रारंभिक_तिथिlast_type | last_type_initial_date | ||
---|---|---|---|---|
ए | मोबाइल | 2019-01-10 00:00:00 | डेस्कटॉप | 2021-01-03 00:00:00 |