Insert the table data based on grouping of two columns
It might be as simple as this:
SELECT Dcode, start_date, end_date, SID FROM ( SELECT Dcode, SID, TRUNC(start_date, 'MONTH') AS start_date , LAST_DAY(end_date) AS end_date , ROW_NUMBER() OVER ( PARTITION BY Dcode ORDER BY total_qty DESC ) AS rn FROM ( SELECT Dcode, SID, MIN(TDT) AS start_date, MAX(TDT) AS end_date , SUM(QTY) AS total_qty FROM mytable GROUP BY Dcode, SID )) WHERE rn = 1
In the inner most subquery I aggregation to get the range of dates and total quantity for particular values of Dcode
and SID
. Then I use an anaylitic (window) function to get the row for which total quantity is the greatest. (You would want to use RANK()
in place of ROW_NUMBER()
in the event you want to return more than one value of SID with the same quantity.)
Here's one option which doesn't contain JLID = 111 in the final result as I have no idea where you took it from.
SQL> with test (jlid, dcode, sid, tdt, qty) as 2 (select 8295783, 3119255, 9842, date '2018-03-05', 14 from dual union 3 select 8269771, 3119255, 9842, date '2018-08-22', 11 from dual union 4 select 8302211, 3119255, 1126, date '2018-03-01', 19 from dual union 5 -- 6 select 1234567, 1112223, 1000, date '2018-06-16', 88 from dual 7 ) 8 select dcode, 9 min (trunc (tdt, 'mm')) start_dt, --> MIN 10 max (last_day (tdt)) end_dt, --> MAX 11 sid 12 from (select dcode, 13 sid, 14 tdt, 15 sqty, 16 rank () over (partition by dcode order by sqty desc) rnk 17 from (select dcode, 18 sid, 19 tdt, 20 sum (qty) over (partition by dcode, sid) sqty 21 from test)) 22 where rnk = 1 23 group by dcode, sid; --> GROUP BY DCODE START_DT END_DT SID---------- ---------------- ---------------- ---------- 1112223 01.06.2018 00:00 30.06.2018 00:00 1000 3119255 01.03.2018 00:00 31.08.2018 00:00 9842SQL>