oracle 解决查询结构问题

tvz2xvvm  于 2022-11-03  发布在  Oracle
关注(0)|答案(1)|浏览(133)

在下面的查询中,我必须使用顶部的注解行,同时我必须以这种格式(按月份分组)保留图片中的这两列。
https://i.stack.imgur.com/3uabV.png

select  --REPLACE(SUBSTR(p.prod_desc,20,200),'size XXXL','size 14.00') ||':PRODUCT_ID='||p.PROD_ID as "PRODUCT_DESCRIPTION",
CASE WHEN t.CALENDAR_WEEK_NUMBER = 13 THEN 'First week'
         WHEN t.CALENDAR_WEEK_NUMBER = 14 THEN 'Second week'
         WHEN t.CALENDAR_WEEK_NUMBER = 15 THEN 'Third week'
         WHEN t.CALENDAR_WEEK_NUMBER = 16 THEN 'Fourth week'
         WHEN t.CALENDAR_WEEK_NUMBER = 17 THEN 'Fifth week'
    END as "WEEK_IN_MONTH",
        sum(s.AMOUNT_SOLD) as TOTAL_AMOUNT_SOLD   
from TIMES t join SALES s
    on t.TIME_ID = s.TIME_ID
  JOIN PRODUCTS p
    on p.PROD_ID = s.PROD_ID
where t.CALENDAR_MONTH_DESC = '2000-04'
      and p.PROD_ID in (300,10,540)
group by t.CALENDAR_WEEK_NUMBER
HAVING sum(s.AMOUNT_SOLD) > 0;
t98cgbkg

t98cgbkg1#

如果我没理解错的话,你的问题是--如果你取消注解那个代码的replace部分--你必须把它包含到group by子句中。
字面意思是:

SELECT    REPLACE (SUBSTR (p.prod_desc, 20, 200), 'size XXXL', 'size 14.00')
         || ':PRODUCT_ID='
         || p.prod_id AS "PRODUCT_DESCRIPTION",
         CASE
            WHEN t.calendar_week_number = 13 THEN 'First week'
            WHEN t.calendar_week_number = 14 THEN 'Second week'
            WHEN t.calendar_week_number = 15 THEN 'Third week'
            WHEN t.calendar_week_number = 16 THEN 'Fourth week'
            WHEN t.calendar_week_number = 17 THEN 'Fifth week'
         END AS "WEEK_IN_MONTH",
         SUM (s.amount_sold) AS total_amount_sold
    FROM times t
         JOIN sales s ON t.time_id = s.time_id
         JOIN products p ON p.prod_id = s.prod_id
   WHERE     t.calendar_month_desc = '2000-04'
         AND p.prod_id IN (300, 10, 540)
GROUP BY t.calendar_week_number,
            REPLACE (SUBSTR (p.prod_desc, 20, 200),
                     'size XXXL',
                     'size 14.00')
         || ':PRODUCT_ID='
         || p.prod_id
  HAVING SUM (s.amount_sold) > 0;

另一个选择是聚合代码的replace部分,这样就不需要将其放在group by中:

SELECT MAX (
               REPLACE (SUBSTR (p.prod_desc, 20, 200),
                        'size XXXL',
                        'size 14.00')
            || ':PRODUCT_ID='
            || p.prod_id) AS "PRODUCT_DESCRIPTION",
         CASE
            WHEN t.calendar_week_number = 13 THEN 'First week'
            WHEN t.calendar_week_number = 14 THEN 'Second week'
            WHEN t.calendar_week_number = 15 THEN 'Third week'
            WHEN t.calendar_week_number = 16 THEN 'Fourth week'
            WHEN t.calendar_week_number = 17 THEN 'Fifth week'
         END AS "WEEK_IN_MONTH",
         SUM (s.amount_sold) AS total_amount_sold
    FROM times t
         JOIN sales s ON t.time_id = s.time_id
         JOIN products p ON p.prod_id = s.prod_id
   WHERE     t.calendar_month_desc = '2000-04'
         AND p.prod_id IN (300, 10, 540)
GROUP BY t.calendar_week_number
  HAVING SUM (s.amount_sold) > 0;

相关问题