简体   繁体   English

Oracle SQL分组依据

[英]Oracle SQL group by

I have below data in my table, 我表中有以下数据,

    Id month value

    1  Jun  20
    1  Jul  22
    1  Aug  0
    1  Sep  12
    2  Jun  21
    2  Jul  45

I need to group them as 我需要将它们分组为

Id Jun Jul Aug Sep
1   20  22 0   12
2   21  45

I am not sure what syntax i should use. 我不确定应该使用哪种语法。 Help appreciated 感谢帮助

@Gurwinder's answer is workable. @Gurwinder的答案是可行的。 Also you can use pivot (in Oracle 11 or above): 您也可以使用数据透视表(在Oracle 11或更高版本中):

select *
 from (
  select id, month, value
    from your_table    
)
pivot (
      max(value)
      for month in ('Jun' as "Jun", 'Jul' as "Jul", 'Aug' as "Aug", 'Sep' as "Sep")
)t

Please try below: 请尝试以下:

select id,
    sum(decode(month, 'Jun', value)) jun,
    sum(decode(month, 'Jul', value)) jul,
    sum(decode(month, 'Aug', value)) aug,
    sum(decode(month, 'Sep', value)) sep
from my_table group by id

You did not mention the version of Oracle. 您没有提到Oracle的版本。 If you are using Oracle 11g or above, the following example would get you close. 如果您使用的是Oracle 11g或更高版本,则以下示例将使您入门。

create table pivot_test (id number(1), month varchar2(3), value number(2));

insert into pivot_test values (1, 'Jun', 20);
insert into pivot_test values (1, 'Jul', 22);
insert into pivot_test values (1, 'Aug', 0);
insert into pivot_test values (1, 'Sep', 12);
insert into pivot_test values (2, 'Jun', 21);
insert into pivot_test values (2, 'Jul', 45);
commit;

select *
from (select id, month, sum(value) as value from pivot_test group by id, month)
pivot (SUM(value) for (month) in ('Jun', 'Jul', 'Aug', 'Sep'))
order by id
;

It yields the following result. 它产生以下结果。

        ID      'Jun'      'Jul'      'Aug'      'Sep'
---------- ---------- ---------- ---------- ----------
         1         20         22          0         12
         2         21         45                      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM