简体   繁体   中英

SQL Query in Apex if date not exist return value from previous date

I need to generate interactive report in Oracle Apex by comparing 2 tables. Each table has Columns: Date, Tag, Number.

Table 1: contains History of the changes of Column: Number and writes on which date the column: Number was changed.

Table 2 : Also has column: Number and column: Date (column: Date which shows different values for column: Number for the different dates of the month).

The Report is being generated when comparing columns "Tag_id" between table 1 and table 2 so we know which value from column: number in table 1 is referring to column: number in table 2. (...where table1.tag=table2.tag).

Table 2 contains date in column: number for every day of the month, and Table 1 contains date that is changed in column: number once every 1,2,3 or more days.

I want the report to show values from column: Number from Table 1 and to show the values from column: Number from Table 2 while making comparison between table 1 and table 2 by column: Date.

The problem is when in Table 1 there is no date in column:Date which is equal to date in column:Date in Table 2, the Database doesnt know which value for column:Number to return in the Generated Report.

What I want to achieve: When there is no date match in the columns:Date between Table 1 and Table 2 I want in the Generated report in Apex to return the value from column:Number from Table 2 for the Date for which there is no match* and the value of column:Number from Table 1 for the closest previous date by using only SQL Query.

表

Interesting question. I don't know about Apex, but if it were Oracle's MySQL, I'd go along the way of:

SELECT 
   t2.id, 
   t2.date,
   CASE WHEN t1.date IS NULL 
      THEN (SELECT table1.number FROM table1 WHERE table1.data <= t2.data ORDER BY table1.data DESC LIMIT 1) 
      ELSE t1.number 
   END AS numberT1,
   t2.number as numberT2
FROM table2 t2
LEFT JOIN table1 t1 ON t1.date = t2.date

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