Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to PIVOT columns based on the date

CREATE TABLE region (
    region_name  VARCHAR2(255),
    region_date  DATE
);

INSERT INTO region VALUES('Paris','23-01-15');
INSERT INTO region VALUES('Paris','28-01-15');
INSERT INTO region VALUES('France','23-01-16');
INSERT INTO region VALUES('France','22-07-17');
INSERT INTO region VALUES('France','21-01-17');
INSERT INTO region VALUES('Germany','25-01-18');

COMMIT;

I need a SELECT query where I would require DISTINCT region_name and based on the region_date. SELECT query should have 5 columns as region_name year_1 year_2 year_3 year_4 wherein year_1 is 2015 year_2 is 2016 and so on. Based on the region_name I need a COUNT for the region_date that how many regions fall in the same year. Below is my expected result

REGION_NAME Year_1 Year_2 Year_3 Year_4
Paris 2 0 0 0
France 0 1 2 0
Germany 0 0 0 1

For Paris – for Year_1 – It has 2 records so the count is 2 for year_1 and for rest it is 0.
Likewise, for all. I am wondering if this can be done.

Note: I have to restrict the report till the year 2018 only. If anything comes after 2018 then that will be included in the report

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tool used: SQL Developer(18c)

>Solution :

You can use pivot to do so:

Schema and insert statements:

 CREATE TABLE region (
     region_name  VARCHAR2(255),
     region_date  DATE
 );

 INSERT INTO region VALUES('Paris','23-JAN-15');
 INSERT INTO region VALUES('Paris','28-JAN-15');

 INSERT INTO region VALUES('France','23-JAN-16');
 INSERT INTO region VALUES('France','22-JUL-17');
 INSERT INTO region VALUES('France','21-JAN-17');
 INSERT INTO region VALUES('Germany','25-JAN-18');

Query:

  select * from
  (SELECT region_name, extract(year from region_date)yr FROM region )
  pivot
  (
  COUNT(*) for yr  in (2015,2016,2017,2018)
  )

Output:

REGION_NAME 2015 2016 2017 2018
Paris 2 0 0 0
France 0 1 2 0
Germany 0 0 0 1

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading