如何将行数限制为3,并将一周中每一天的金额相加?

时间:2019-06-14 13:41:10

标签: oracle

我需要将结果分别汇总到4月,5月和6月的3行中,而我要获得这3行在每周的每一天(周一至周日)的总和。但这没用。

select distinct t.calendar_month_name as "SALES_MONTH", 
case when t.day_number_in_week = 1 then sum(s.amount_sold) else 0 end as MONDAY,
case when t.day_number_in_week = 2 then sum(s.amount_sold) else 0 end as TUESDAY,
case when t.day_number_in_week = 3 then sum(s.amount_sold) else 0 end as WEDNESDAY,
case when t.day_number_in_week = 4 then sum(s.amount_sold) else 0 end as THURSDAY,
case when t.day_number_in_week = 5 then sum(s.amount_sold) else 0 end as FRIDAY,
case when t.day_number_in_week = 6 then sum(s.amount_sold) else 0 end as SATURDAY,
case when t.day_number_in_week = 7 then sum(s.amount_sold) else 0 end as SUNDAY
from products p
join sales s on p.prod_id = s.prod_id
join times t on t.time_id = s.TIME_ID
where
p.prod_id = 5  and 
t.calendar_year = 2000 and
t.calendar_quarter_number = 2
group by t.calendar_month_name, t.day_number_in_week
having sum(s.amount_sold) > 1
order by 1;

1 个答案:

答案 0 :(得分:1)

您在这里不需要PROD表。在我的SH模式中,我没有PROD_ID = 5,所以我使用了13。

select * from (
  select t.calendar_month_name, t.day_number_in_week,
    sum(s.amount_sold) amount_sold
  from sales s
  join times t on t.time_id = s.TIME_ID
  where
  s.prod_id = 13  and 
  t.calendar_year = 2000 and
  t.calendar_quarter_number = 2
  group by t.calendar_month_name, t.day_number_in_week
  having sum(s.amount_sold) > 1
)
pivot(sum(amount_sold) for day_number_in_week in (
  1 as MONDAY,
  2 as TUESDAY,
  3 as WEDNESDAY,
  4 as THURSDAY,
  5 as FRIDAY,
  6 as SATURDAY,
  7 as SUNDAY
))
order by 1;

CALENDAR_     MONDAY    TUESDAY  WEDNESDAY   THURSDAY     FRIDAY   SATURDAY     SUNDAY
--------- ---------- ---------- ---------- ---------- ---------- ---------- ----------
April       20792,32   35724,12   43189,77   16688,08    11436,9              49960,37
June        27037,04   16809,54   11504,03              37709,26   23923,83   35908,33
May                   123982,43   18773,74               5283,56              21167,23

如果没有HAVING过滤器,则在内联视图中不需要GROUP BY,因为PIVOT子句的隐式分组就足够了:

select * from (
  select t.calendar_month_name, t.day_number_in_week,
    s.amount_sold
  from sales s
  join times t on t.time_id = s.TIME_ID
  where
  s.prod_id = 13  and 
  t.calendar_year = 2000 and
  t.calendar_quarter_number = 2
)
pivot(sum(amount_sold) for day_number_in_week in (
  1 as MONDAY,
  2 as TUESDAY,
  3 as WEDNESDAY,
  4 as THURSDAY,
  5 as FRIDAY,
  6 as SATURDAY,
  7 as SUNDAY
))
order by 1;

最好的问候, 炖阿什顿