简体   繁体   中英

How to compare value of month and day from a date in oracle 11g and use it in where clause?

I have a table 'table1' where months of a year are numbered from 1 to 12 in rows and 1 to 31 days of month are in form of column.

There is another table 'table2' where dates and some other values are stored. The date has DATE datatype. I need to fetch date from that 'table2' and compare values of month and day and insert values into 'table1' accordingly. Example if date from 'table2' is 21-JUN-2017, then value should be inserted in 21st colunm(day) and 6th row(month) in 'table1'. How can I implement the same in Oracle 11g using SQL?

Thanks for the help in advance.

Oracle Setup :

Simplify your table - do not store 32 columns (month and 31 days) instead just store month, day and value and PIVOT the output as required:

CREATE TABLE table1 (
  month NUMBER(2,0),
  day   NUMBER(2,0),
  value VARCHAR2(4000)
);

INSERT INTO table1
  SELECT EXTRACT( MONTH FROM date_column ),
         EXTRACT( DAY   FROM date_column ),
         value
  FROM   table2;

Query :

SELECT month, d1, d2, d3, d4, /* ..., */ d31
FROM   table1
PIVOT  ( MAX( value ) FOR day IN (
           1 AS d1, 2 AS d2, 3 As d3, 4 AS d4, /* ..., */ 31 AS d31
       ) );

Update :

DDL for table1:-

 CREATE TABLE table1 (Month Number,1 Number,2 Number,...31 Number,); 

You can use:

INSERT INTO table1
  SELECT month, d1, d2, /* ..., */ d31
  FROM   ( SELECT EXTRACT( MONTH FROM date_column ) AS month,
                  EXTRACT( DAY   FROM date_column ) AS day,
                  value
           FROM   table2 )
  PIVOT  ( MAX( value ) FOR day IN (
             1 AS d1, 2 AS d2, /* ..., */ 31 AS d31
         ) );

Or use MERGE INTO if you want to update the existing rows.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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