I want to display Day name based on ID which is in bigint[] in the table as shown below:
Table:
create table tbl_days
(
day_ids bigint[]
);
Records:
insert into tbl_days values('{1,2}');
insert into tbl_days values('{1,2,3}');
insert into tbl_days values('{1,4}');
insert into tbl_days values('{4,7}');
insert into tbl_days values('{1,2,3,4,5,6,7}');
insert into tbl_days values('{2,4,7}');
Would like to display day name for:
1 for Monday
2 for Tuesday
.
..
7 for Sunday.
Query 1: Using replace()
, which is taking 3 more seconds to get the main query result.
select replace(replace(replace(replace(replace(replace(replace(day_ids::varchar,'1','Monday'),'2','Tuesday'),'3','Wednesday'),'4','Thursday'),'5','Friday'),'6','Saturday'),'7','Sunday')
from tbl_days;
Query 2: Using string_agg()
, here problem with an order.
Step 1: Add days into temp table
create temp table temp_days
(
id int,
days varchar
);
insert into temp_days values(1,'Monday'),(2,'Tuesday'),(3,'Wednesday'),(4,'Thursday'),(5,'Friday'),(6,'Saturday'),(7,'Sunday');
Step 2: Join with main table
select d.day_ids,string_agg(distinct t.days,',')
from tbl_days d
inner join temp_days t on t.id = any(d.day_ids)
group by d.day_ids
question from:
https://stackoverflow.com/questions/65682046/get-day-name-based-on-custome-id-of-bigint-datatype