一行中的oracle sql查询次数

6za6bjd0  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(336)

我为任何格式问题提前道歉。
下面是一些示例数据。

以下是我想要制作的:

下面是我使用一系列case-when语句得到的结果

任何编码帮助都非常感谢。

wfveoks0

wfveoks01#

您需要聚合:

select id,
       sum(case when quarter = 1 then sales end) as q1_sales,
       sum(case when quarter = 2 then sales end) as q2_sales,
       sum(case when quarter = 3 then sales end) as q3_sales,
       sum(case when quarter = 4 then sales end) as q4_sales
from t
group by id;
2w2cym1i

2w2cym1i2#

这就是创建pivot子句的目的:

-- sample data:
with t(id, quarter, sales) as (
   select 1,1,13 from dual union all
   select 1,2,14 from dual union all
   select 1,3,21 from dual union all
   select 1,4,17 from dual union all
   select 2,1,11 from dual union all
   select 2,2,23 from dual union all
   select 2,3,18 from dual union all
   select 2,4,19 from dual 
)
-- query:
select *
from t
pivot(
  sum(sales) 
  for Quarter in (
        1 as Q1
       ,2 as Q2
       ,3 as Q3
       ,4 as Q4)
);

        ID         Q1         Q2         Q3         Q4
---------- ---------- ---------- ---------- ----------
         1         13         14         21         17
         2         11         23         18         19

相关问题