Home > database >  How to use case expression or should go for any other option
How to use case expression or should go for any other option

Time:09-07

I have a table that looks something like this, Report_Table:

Report_DEFINITION_NAME Report_CORE_NAME COMPLETION_STATUS COMPLETION_DATE
ReportAD AD Success 14-01-2019
ReportBB BB Error 24-06-2022
ReportAD AD Error 19-03-2020
ReportR5 R5 Success 04-06-2022
ReportG8 G8 Error 04-06-2022
ReportR5 R5 Success 18-11-2020
ReportLH LH Success 07-09-2019
ReportU6 U6 Error 12-05-2022
ReportAD AD Success 23-09-2021

I wanted to pull data from Report_table. If COMPLETION_STATUS is Success it should give the latest Success COMPLETION_DATE table date and if it has Error it should give the last Success COMPLETION_DATE table date as well as the Error date. Something like

select Report_DEFINITION_NAME, Report_Core_name, COMPLETION_STATUS, COMPLETION_DATE,

CASE: WHEN COMPLETION_STATUS='Success' THEN latest Success COMPLETION_DATE WHEN COMPLETION_STATUS='Error' THEN last Success COMPLETION_DATE WHEN COMPLETION_STATUS='Error' THEN latest Error COMPLETION_DATE END

from Report_Table;

the output should be in a single query identified by core name or definition name.

CodePudding user response:

So, I have used IN clause to solve my problem and no Case expression.

Getting the max value in a select statement and calling that statement using IN clause from my parent select statement solved my problem. something like:

SELECT 
  a.*,
  a.completion_date,
  b.completion_date AS last_success_date
FROM report_table a, report_table b
WHERE a.report_definition_name = b.report_definition_name
AND a.completion_date IN 
(
  SELECT MAX(su.completion_date) 
  FROM report_table su 
  WHERE su.completion_status = 'Success'
  AND b.report_definition_name = su.report_definition_name
)
ORDER BY a.completion_date DESC;
  • Related