Oracle 11g histogram row-to-column, 11 gpivot

Source: Internet
Author: User

Oracle 11g histogram row-to-column, 11 gpivot

I have written a line-to-column article: Oracle simple column-to-row

SQL> select * from v $ version;

BANNER
--------------------------------------------------------------------------------
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0-64bit Production
PL/SQL Release 11.2.0.1.0-Production
CORE 11.2.0.1.0 Production
TNS for Linux: Version 11.2.0.1.0-Production

NLSRTL Version 11.2.0.1.0-Production

The requirement is to count the total salaries of different jobs in each department.

SQL> select deptno, ename, job, sal from emp;
DEPTNO ENAME JOB SAL
---------------------------------------
20 smith clerk 800
30 allen salesman 1600
30 WARD sales man 1250
20 jones manager 2975
30 martin salesman 1250
30 blake manager 2850
10 clark manager 2450
20 scott analyst 3000
10 king president 5000
30 turner salesman 1500
20 adams clerk 1100
30 james clerk 950
20 FORD analytic 3000
10 miller clerk 1300
14 rows have been selected.

SQL> select deptno,
Nvl (sum (decode (job, 'manager', sal), 0) "s_MANAGER ",
Nvl (sum (decode (job, 'analyst', sal), 0) "s_ANALYST ",
Nvl (sum (decode (job, 'cler', sal), 0) "s_cler ",
Nvl (sum (decode (job, 'President ', sal), 0) "s_PRESIDENT ",
Nvl (sum (decode (job, 'salesman', sal), 0) "s_SALESMAN"
From emp
Group by deptno;
DEPTNO s_MANAGER s_ANALYST s_clers_president s_SALESMAN
-------------------------------------------------------------
30 2850 0 950 0 5600
20 2975 6000 1900 0 0
10 2450 0 1300 5000 0

It will be simpler to use tokens.

SQL> with p as (select deptno, job, sal from emp)
SELECT * FROM p round (SUM (sal)
FOR job IN ('manager' as "s_MANAGER ",
'Analyst' as "s_ANALYST ",
'Cler' as "s_cler ",
'President 'as "s_PRESIDENT ",
'Salesman' as "s_SALESMAN "));
DEPTNO s_MANAGER s_ANALYST s_clers_president s_SALESMAN
-------------------------------------------------------------
30 2850 950 5600
20 2975 6000 1900
10 2450 1300 5000

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.