I have two tables and the data in table 1 is in rows. Key column in table 1 has the columns that are as rows now and want to trasnform to column Below is how i have the table now.
The data i have in table 1 is as below
Table 1
tickedt_ID Key Value Created_at
1 123 Free 2023-06-01
1 type task 2023-06-01
1 status open 2023-06-01
1 channel email 2023-06-01
1 456 fruit 2023-06-01
2 123 paid 2023-06-01
2 type incident 2023-06-01
2 status closed 2023-06-01
2 channel voice 2023-06-01
2 456 vegetable 2023-06-01
Table 2 has the created at date which i need to join with table 1 and also need to join subject and type.
Table 2
ID Created_at type subject
1 2023-06-01 task XXX
2 2023-06-01 incident abc
3 2023-06-01 task def
Code i tried quering
select t.ticket_id,t.created_at,t.value
min(case when t.key = 123 then t.value end) as plan,
min(case when t.key = 456 then t.value end) as category
from t1 t
join t2 te on t.ticket_id = te.id
where t.created_at > '2023-06-01' and t.created_at <= '2023-06-21'
GROUP by t.id,t.created_at
when i try this the id is getting repeated again because they key has got multiple values and i am not able to group by the id
Expected output
ID. 123(rename as plan) status. 456(rename as category). type. created at
1 Free open Fruit task 2023-06-01
2 Paid closed vege incident 2023-06-01
2
Answers
Your data wouldn’t return anything with that where criteria (no date is after 2023-06-01). Assuming that was a typo:
DBFiddle demo
Assuming that the table t1 has just one occurrence of distinct keys for each id, I believe you could use subselects to get the columns you want. Try like something this, and extend it with JOIN/WHERE/GROUP BY clauses as needed.