Hi @Kati_14 ,
Welcome to Microsoft Q&A!
For this type of problem we recommend that you post CREATE TABLE statements for your tables together with INSERT statements with sample data as below.
create table WELLS
(lease varchar(20),
API int,
Operator varchar(20),
State varchar(20),
County varchar(20))
insert into WELLS values
('Harbor', 1, '4256820125', 'Devon Howard', 'Tx')
create table PRODUCTION
(API int,
SOURCE varchar(20),
OUTDATE date,
GAS int,
OIL int)
insert into PRODUCTION values
(1,'MP','1/1/2020', 546, 948),
(1,'MP','2/1/2020', 572, 1001),
(1,'MP','3/1/2020', 506, 1119),
(1,'MP','4/1/2020', 499, 968),
(1,'MP','5/1/2020', 599, 1165),
(1,'MP','6/1/2020', 544, 1065),
(1,'MP','7/1/2020', 492, 1267),
(1,'MP','8/1/2020', 546, 988),
(1,'MP','9/1/2020', 566, 932),
(1,'MP','10/1/2020', 496, 1103),
(1,'MP','11/1/2020', 465, 1075),
(1,'MP','12/1/2020', 598, 1222),
(1,'MP','1/1/2021', 565, 1026)
create table MONTHLY
(API int,
SOURCE varchar(20),
OUTDATE date,
Gross_Oil int,
Gross_gas int)
insert into MONTHLY values
(1,'FCST','1/1/2021', 532, 1019),
(1,'FCST','2/1/2021', 625, 798),
(1,'FCST','3/1/2021', 614, 965),
(1,'FCST','4/1/2021', 600, 865),
(1,'FCST','5/1/2021', 597, 845),
(1,'FCST','6/1/2021', 532, 802),
(1,'FCST','7/1/2021', 512, 812),
(1,'FCST','8/1/2021', 500, 784),
(1,'FCST','9/1/2021', 495, 784),
(1,'FCST','10/1/2021', 465, 684),
(1,'FCST','11/1/2021', 432, 656),
(1,'FCST','12/1/2021', 412, 632),
(1,'FCST','3/1/2021', 400, 444)
Please provide more details about the duplicated rows of '3/1/2021'. Need we remain or remove the duplicated row?
Please refer below statement and check whether it is helpful:
;with cte as (
select ac.[LEASE] as WELL,
ac.[API],
ac.[OPERATOR],
ac.[STATE],
ac.[COUNTY],
mp.[SOURCE],
mp.[OUTDATE],
mp.[GAS] as GAS_PROD,
mp.[OIL] as OIL_PROD,
NULL OIL_FCST,
NULL GAS_FCST
from WELLS ac
inner join PRODUCTION mp
on ac.API = mp.API
union
select ac.[LEASE] as WELL,
ac.[API],
ac.[OPERATOR],
ac.[STATE],
ac.[COUNTY],
fcst.SOURCE,
fcst.OUTDATE,
NULL GAS_PROD,
NULL OIL_PROD,
fcst.Gross_Gas,
fcst.Gross_Oil
from WELLS ac
INNER JOIN MONTHLY fcst
ON ac.API = fcst.API
),cte1 as (
select *,ROW_NUMBER() over (partition by outdate order by (IIF(source='MP',1,2)),GAS_FCST desc) rn
from cte)
select well,api,Operator,State,County,SOURCE,OUTDATE,GAS_PROD,OIL_PROD,GAS_FCST,OIL_FCST
from cte1 where rn=1
Output:
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.