I have two tables by names CASTR
and CABL
. My query is
SELECT to_number(substr(CASTR_OPER_DATE, 1, 5))
,MAX(CABL_REL_DAY)
,CASTR_KW_CAAC
,cabl_avail_bal
FROM CASTR
INNER JOIN CABL
ON CASTR_KW_CAAC = CABL_KW_CAAC
WHERE CABL_REL_DAY <= to_number(substr(CASTR_OPER_DATE, 1, 5))
GROUP BY CASTR_OPER_DATE, CASTR_KW_CAAC, cabl_avail_bal
when I run this query it gives me all cabl_avail_bal
columns, but I want only cabl_avail_bal
which their cabl_rel_day
is max and CABL_REL_DAY<=to_number(substr(CASTR_OPER_DATE,1,5))
condition is true.
Here is my table structures
Kindly try the below
WITH CABL_REL_DAY_MAX
as
(SELECT to_number(substr(CASTR_OPER_DATE, 1, 5)) oper_date
,MAX(CABL_REL_DAY) cabl_rel_max
,CASTR_KW_CAAC
FROM CASTR
INNER JOIN CABL
ON CASTR_KW_CAAC = CABL_KW_CAAC
WHERE CABL_REL_DAY <= to_number(substr(CASTR_OPER_DATE, 1, 5))
GROUP BY CASTR_OPER_DATE, CASTR_KW_CAAC)
select oper_date,
cabl_rel_max,
CASTR_KW_CAAC,
CABL.cabl_avail_bal
FROM CABL
INNER JOIN CABL_REL_DAY_MAX
ON CASTR_KW_CAAC = CABL_KW_CAAC
WHERE CABL.CABL_REL_DAY=cabl_rel_max;
I would suggest using analytic functions, something like this:
SELECT to_number(substr(CASTR_OPER_DATE, 1, 5)), CABL_REL_DAY, CASTR_KW_CAAC, cabl_avail_bal
FROM (SELECT CASTR_OPER_DATE, CABL_REL_DAY, CASTR_KW_CAAC, cabl_avail_bal,
row_number() over (partition by CASTR_KW_CAAC order by cable_rel_day desc) as seqnum
FROM CASTR INNER JOIN
CABL
ON CASTR_KW_CAAC = CABL_KW_CAAC
WHERE CABL_REL_DAY <= to_number(substr(CASTR_OPER_DATE, 1, 5))
) c
WHERE seqnum = 1;
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.