Displaying LISTAGG values in a cell based on the value of another column

三世轮回 提交于 2019-12-25 03:11:33

问题


I am working on an assignment and I'm very close to finishing however, I have been struggling with one bit of it for a while. I need to display a table that has a SCHEDULE column, and a DAYS column where the DAYS column shows a list of days based on the SCHEDULE. There are only two options for SCHEDULE: 'Weekend' and 'Weekday.'

Here is the end result that I am trying to achieve:

ID   Schedule     Days
001  Weekend      Saturday, Sunday

I have created a process and am using this code:

BEGIN
UPDATE schedules
SET days =
        WHEN schedule = 'Weekend' THEN
        (SELECT LISTAGG(day, ', ') WITHIN GROUP (ORDER BY day_order)
        FROM days
        WHERE schedule = 'Weekend'
        )
        WHEN schedule = 'Weekday' THEN
        (SELECT LISTAGG(day, ', ') WITHIN GROUP (ORDER BY day_order)
        FROM days
        WHERE schedule = 'Weekday'
        )
    END

When I do this, I get the error:

Encountered the symbol "end-of-file" when expecting one of the following: begin function pragma procedure

If anyone can give me a hand, it would be much appreciated!


回答1:


Your update is equivalent to this.

UPDATE schedules s 
SET    days = (SELECT LISTAGG(day, ', ') 
                        within group ( ORDER BY day_order ) 
               FROM   days d 
               WHERE  d.schedule IN ( 'Weekend', 'Weekday' ) 
                      AND d.schedule = s.schedule 
               GROUP  BY d.schedule ) ;

But, I would not recommend this. Storing the records as comma separated values is bound to cause problems for you in future. Only use it to display the results using a query like below. This assumes that in your days table, there are unique rows for each day.If there are duplicates, join it to the distinct result set from days.

SELECT d.id, 
       d.schedule, 
       LISTAGG(s.day, ', ') 
         within GROUP ( ORDER BY d.day_order ) 
FROM   days d 
       join schedules s 
         ON ( d.schedule = s.schedule ) 
WHERE  d.schedule IN ( 'Weekend', 'Weekday' ) 
GROUP  BY d.id, 
          d.schedule 



回答2:


You can use a MERGE statement:

MERGE INTO schedules dst
USING (
  SELECT schedule,
         LISTAGG( day, ', ' ) WITHIN GROUP ( ORDER BY day_order ) AS days
  FROM   days
  GROUP BY schedule
) src
ON ( dst.schedule = src.schedule )
WHEN MATCHED THEN
  UPDATE SET days = src.days;

But you would probably be better to not store values in a delimited list and just use a foreign key reference between schedules.schedule and days.schedule to connect the two tables.



来源:https://stackoverflow.com/questions/50365445/displaying-listagg-values-in-a-cell-based-on-the-value-of-another-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!