基于另一列值展示LISTAGG结果(续篇)
Got it, let's work through this step by step. First off, you're right to move away from storing comma-separated lists in your tables— that's an anti-pattern that'll cause headaches down the line with maintenance and data consistency. The good news is we can use Oracle's LISTAGG function directly in a query to get the formatted output you need, no updates required.
Let's Break Down the Query
Your table structure is properly normalized with the junction table DAY_SCHEDULES, so we just need to join the tables correctly and aggregate the day names. Here's the query that should give you the exact output you want:
SELECT s.Schedule_ID AS ID, s.Schedule, LISTAGG(d.Day_Name, ', ') WITHIN GROUP (ORDER BY d.Day_Order) AS Days FROM SCHEDULES s INNER JOIN DAY_SCHEDULES ds ON s.Schedule_ID = ds.Schedule_ID INNER JOIN DAYS d ON ds.Day_ID = d.Day_ID GROUP BY s.Schedule_ID, s.Schedule ORDER BY s.Schedule_ID;
Why This Works
- Joins: We're linking the
SCHEDULEStable to the junction tableDAY_SCHEDULESviaSchedule_ID, then connecting toDAYSviaDay_ID. This pulls all the days associated with each schedule. - LISTAGG: This function aggregates the
Day_Namevalues into a single comma-separated string. TheWITHIN GROUP (ORDER BY d.Day_Order)ensures the days are listed in the correct order (e.g., Saturday before Sunday for Weekend). - Grouping: We group by
Schedule_IDandSchedulebecause you want one row per schedule entry (matching your example where ID 001 is a single Weekend schedule).
Addressing Your Case Statement Issue
If your earlier CASE approach wasn't returning results, it's likely because CASE alone can't aggregate multiple rows into a single value. You need an aggregation function like LISTAGG to combine those day names into one cell— that's the missing piece from your initial attempt.
The "No Foreign Key" Concern
You mentioned you can't create a foreign key between DAYS.Schedule and SCHEDULES.Schedule because the Schedule column isn't unique. That's totally fine! Your junction table DAY_SCHEDULES is already handling the relationship correctly by linking Schedule_ID (the unique primary key of SCHEDULES) to Day_ID (the unique primary key of DAYS). You don't need a direct foreign key between the Schedule columns— that's not how normalized schema design works here.
Using This in Oracle APEX
To display this in an APEX table:
- Create an Interactive Report or Classic Report on your page.
- Paste the query above as the report's source.
- Adjust column aliases or formatting as needed (e.g., make the
Dayscolumn wrap text if needed).
This approach is optimal because it pulls real-time data directly from your normalized tables— no need to maintain redundant comma-separated lists that can get out of sync when days or schedules are updated.
内容的提问来源于stack exchange,提问作者HSN

