Hi @steffimeister ,
Welcome to the microsoft TSQL Q&A forum!
If you want to sum the rows that exist in the externalRoomMap table but are not affected by Change tracking, you need to use right join to connect all the roomcodes first.
In addition, in the final summation, you need to use sum() over() instead of sum group.
Please refer to:
create table tblavailable(dtm date,hotelid int,roomcode char(15) primary key ,intqty int)
insert into tblavailable values('2000-01-04',23,'ovb',9)
create table externalRoomMap
(hotelid int,roomcode1 char(15),roomcode2 char(15),externalroom int)
insert into externalRoomMap values(23,'svr','ovb',023)
create table externalResortMap
(hotelid int,externalresortid int,hotelname char(15))
insert into externalResortMap values(23,234,'testhotel')
create table tblResorts
(hotelid int,hotelname char(15))
insert into tblResorts values(23,'testhotel')
ALTER TABLE tblAvailable
ENABLE CHANGE_TRACKING
WITH (TRACK_COLUMNS_UPDATED = ON);
insert into tblavailable values('2000-01-04',23,'svr',9)
select distinct a.dtm as InvDate,a.hotelid as ResortId,am.roomcode1 as RoomType,
sum(a.intqty) over(partition by a.dtm,a.hotelid) as InvCount,a.hotelid as externalRoom
from changetable(changes dbo.tblAvailable,0) t
right join tblAvailable a on t.roomcode=a.roomcode
join dbo.tblResorts r on r.hotelid = a.hotelid
join externalResortMap arm on arm.hotelid =a.hotelid
join externalRoomMap am on a.roomcode=am.roomcode1 or a.roomcode=am.roomcode2
Output:
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Regards
Echo
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.