Find matching records in same table different columns - tsql

I have this query:
SELECT
TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D,
TLOCMTR.MTR_XCHG_OUT_D, RATE.RATE, TMTR.MTR_MFR_MOD_C,
TMTR.MTR_MFR_NM_CD
FROM
TMTR
RIGHT OUTER JOIN
TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N
LEFT OUTER JOIN
RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K
WHERE
((RATE.RATE >= 20) AND (RATE.RATE <= 29))
AND TLOCMTR.MTR_INST_D >= '2014-01-01'
ORDER BY
LOCATN_K, MTR_INST_D
The code results in:
What I need to do is count the number of times the MTR_MFR_NM_CD changes from AMP to <>AMP per Locatn_K where the MTR_INST_D = MTR_XCHG_OUT_D. For example LOCATN_K = 85420005 went from AMP to EEM and the MTR_XCHG_D = MTR_INST_D 1 time (date was '2014-08-27'. LOCATN_K 85430001 went from AMP to EEM 2 times on dates '2015-01-05' and '2016-01-12.
Please help me with some T-SQL to answer this!

this is the essentials
select *
from ( select LOCATN_K, MTR_INST_D, MTR_MFR_NM_CD
, LEAD(MTR_MFR_NM_CD, 1,0) OVER (PARTITTION LOCATN_K BY ORDER BY MTR_INST_D) AS MTR_MFR_NM_CD_NEXT
from
...
) tt
where MTR_MFR_NM_CD = 'AMP'
and MTR_MFR_NM_CD_NEXT <> 'AMP'

I tried Frisbee's code with the following modifications but did not get the exact results:
select *
from ( select TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D, TLOCMTR.MTR_XCHG_OUT_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD,
LEAD(TMTR.MTR_MFR_NM_CD, 1,0) OVER (PARTITION BY TLOCMTR.LOCATN_K
ORDER BY MTR_INST_D) AS MTR_MFR_NM_CD_NEXT
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N
LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) AND TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD = 'AMP'
) tt
where tt.MTR_MFR_NM_CD = 'AMP'
and tt.MTR_MFR_NM_CD_NEXT <> 'AMP'
order by tt.LOCATN_K
This resulted in getting 'Amp' to 'Amp' and <>'Amp' to 'Amp', but what I just wanted to get was 'Amp'to <>'Amp'.
The easiest way for me to do this was:
WITH A AS
(SELECT TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_XCHG_OUT_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) and TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD = 'AMP'
),
B AS(
SELECT TLOCMTR.LOCATN_K, TLOCMTR.MTR_SRP_N, TLOCMTR.MTR_INST_D, TMTR.MTR_MFR_MOD_C, TMTR.MTR_MFR_NM_CD
FROM TMTR RIGHT OUTER JOIN TLOCMTR ON TMTR.MTR_SRP_N = TLOCMTR.MTR_SRP_N
LEFT OUTER JOIN RATE ON TLOCMTR.LOCATN_K = RATE.LOCATN_K
WHERE ((RATE.RATE >= 20) AND (RATE.RATE <= 29)) AND TLOCMTR.MTR_INST_D>='2014-01-01' AND TMTR.MTR_MFR_NM_CD <> 'AMP'
)
SELECT A.LOCATN_K, A.MTR_SRP_N AmpyMeter, B.MTR_SRP_N CreditMeter, B.MTR_INST_D EXCG_DT, A.MTR_MFR_MOD_C AMP_MODEL, B.MTR_MFR_MOD_C Credit_MODEL
FROM A inner join B on A.MTR_XCHG_OUT_D = B.MTR_INST_D and A.LOCATN_K=B.LOCATN_K
ORDER BY LOCATN_K
My final results look like:

Related

Postgres OUTER JOINS TABLE ALREADY JOINED

i'm facing issues migrating queries from Oracle to Postgres 15. How can i join a table that is already joined? The Oracle looks like this:
select ltd1.short_description || '_' || to_char( CASE WHEN lsd.origine_type_id = 2 THEN
lsd.data_normalizzazione_mail
ELSE lsd.data_normalizzazione_web
END, 'YYYYMMDD_HH24MISS' ) Transazione,
lkc.kit_name || '_' || lkc.doc_name Documento_Idkit_iddoc,
lp.codice_pratica Pratica,
to_char( CASE WHEN lsd.origine_type_id = 2 THEN lsd.data_normalizzazione_mail ELSE lsd.data_normalizzazione_web END, 'DD/MM/YYYY HH24:MI:SS' ) Data_Inizio,
ltd1.long_description Tipologia_Documento,
CASE WHEN lsd.origine_type_id = 2 THEN 'Digitale' ELSE 'Cartaceo' END Tipologia_Arrivo,
lsc.sla_period || ' ore' Sla,
to_char( lsd.data_fine_trans, 'DD/MM/YYYY HH24:MI:SS' ) Data_Fine_Lavorazione,
ltd2.short_description Fase_Lavorazione,
case when ((lsd.sla_period * 60) - lsd.min_elapsed) <= 0 then 999999999 else ((lsd.sla_period * 60) - lsd.min_elapsed) end Tempo_Residuo,
to_char( lsd.data_prevista_fine_sla, 'DD/MM/YYYY HH24:MI:SS' ) Data_Previsione_Chiusura_SLA,
lsd.alert_sla Alert,
lsd.stato_sla_type_id Stato_Lav,
lsd.in_sla,
lsd.out_of_sla OutSla
from gdf_suez.ld_sla_detail lsd,
gdf_suez.ls_type_description ltd1,
gdf_suez.ld_documenti ld,
gdf_suez.ls_kit_config lkc,
gdf_suez.ld_pratiche lp,
gdf_suez.ls_sla_config lsc,
gdf_suez.ls_type_description ltd2,
gdf_suez.ld_mail lm
where ltd1.context = 'DOC_TYPE_ID'
and ltd1.type_id = lsd.doc_type_id
and ld.trans_id(+) = lsd.trans_id
and lm.trans_id(+) = lsd.trans_id
and lkc.kit_id(+) = ld.kit_id
and lp.pratica_id(+) = ld.pratica_id
and lsc.doc_type_id = lsd.doc_type_id
and lsc.doc_subtype_id = lsd.doc_subtype_id
and lsc.giorno_id = 1
and ltd2.context = 'DOC_STATUS_TYPE_ID'
and ltd2.type_id = lsd.stato_sla_type_id
and decode( lsd.origine_type_id, 2, lsd.data_normalizzazione_mail, lsd.data_normalizzazione_web) between to_date( '2022-02-01', 'YYYY-MM-DD' ) and to_timestamp( '2022-02-28 23:59:59', 'YYYY-MM-DD HH24:MI:SS' )
and lsd.stato_trans_type_id >= 0
and lm.email_stato_type_id not in (6,16)
order by Alert desc, Stato_Lav, Tempo_Residuo
When i try to rewrite it on postgres, the table gdf_suez.ld_documenti ld needs to be joined to 3 tables, and one of those 3 needs to be joined to another table. How do i fix this?
Tried to rewrite the query but the error "table name "ld" specified more than once" is thrown
from gdf_suez.ld_sla_detail lsd
LEFT OUTER JOIN gdf_suez.ld_documenti ld ON lsd.trans_id = ld.trans_id
LEFT OUTER JOIN gdf_suez.ld_mail lm ON lsd.trans_id = lm.trans_id,
gdf_suez.ls_type_description ltd1,
gdf_suez.ld_documenti ld
LEFT OUTER JOIN gdf_suez.ls_kit_config lkc ON ld.kit_id = lkc.kit_id
LEFT OUTER JOIN gdf_suez.ld_pratiche lp ON ld.pratica_id = lp.pratica_id,
gdf_suez.ls_sla_config lsc,
gdf_suez.ls_type_description ltd2
It is always easy to translate from Oracle's outdated outer join syntax to the more powerful syntax of the SQL standard: put everything that has a (+) on the right side of a LEFT JOIN. So your FROM clause would become
FROM gdf_suez.ls_type_description AS ltd1
JOIN gdf_suez.ld_sla_detail AS lsd
ON ltd1.type_id = lsd.doc_type_id
JOIN gdf_suez.ls_sla_config AS lsc
ON lsc.doc_type_id = lsd.doc_type_id
AND lsc.doc_subtype_id = lsd.doc_subtype_id
JOIN gdf_suez.ls_type_description AS ltd2
ON ltd2.type_id = lsd.stato_sla_type_id
LEFT JOIN gdf_suez.ld_mail AS lm
ON lm.trans_id = lsd.trans_id
LEFT JOIN gdf_suez.ld_documenti AS ld
ON ld.trans_id = lsd.trans_id
LEFT JOIN gdf_suez.ls_kit_config AS lkc
ON lkc.kit_id = ld.kit_id
LEFT JOIN gdf_suez.ld_pratiche AS lp
ON lp.pratica_id = ld.pratica_id

Need to replace case statement in where clause

**The below query is working badly, and I'm planning to replace case stmt in where clause with temp table. Pls suggest to me some option to rewrite this query
Is there a way to simplify this into multiple SQLs
Also explain me how this case stmt works in where clause**
select DISTINCT
ph.order_type_cd,
c.order_num,
ph.created_date,
os.order_status_desc,
ph.facility_name,
PH.vendor_order_num,
l.lic_nm,
(u.last_nm + ', ' + u.first_nm )as requestor_nm,
bl.billing_location_desc,
ph.ship_to_name,
dm.dispatch_method_name_desc as courier,
PH.po_last_updated_dt as last_updated_date,
(u1.last_nm + ', ' + u1.first_nm )as last_updated_by,
ph.right_grp_id,
c.line_id,
a.material_product_id,
a.parent_material_product_id
from avt_po_detail c
inner join avt_po_hdr ph on ph.order_num = c.order_num
left outer join avt_material_product AS a on a.material_product_id=c.material_product_id
INNER JOIN #entity_ids po on po.entity_id = c.order_num --or #select_pos = 0 )
LEFT OUTER JOIN dbo.ert_product AS pc ON pc.product_id = a.product_id
left outer join ert_product_type as pt on pt.product_type_cd = pc.product_type_cd
LEFT OUTER JOIN dbo.ert_product_xref as xref on xref.product_id = a.parent_product_id AND xref.version_id = 1
left outer join avt_order_status AS OS ON OS.order_status_cd = PH.order_status_cd
left outer join avt_licensee l on l.lic_id = ph.lic_id
left outer join avt_po_from pf on pf.material_product_id = a.material_product_id and pf.line_id = c.line_id
left outer join avt_po_audio_detail pad on pad.line_id = c.line_id
left outer join avt_materials_trans_material MTM on mtm.sequence_no = c.video_seq_no
left outer join avt_user u on u.userid = ph.requestor_id
left outer join avt_user u1 on u1.userid = ph.po_last_updated_by
left outer join avt_billing_location bl on bl.billing_location_cd = PH.billing_location_cd
left outer join avt_dispatch_method_name dm on dm.dispatch_method_name_id = PH.dispatch_method_name_id
left outer join avt_right_group arg on arg.right_grp_id = ph.right_grp_id
left outer join #prod product on product.product_id=a.product_id and (product.version_id=c.dist_version_id OR product.version_id = 1)
where (pf.from_desc in ( select from_desc from #from_desc ) or #select_form = 0)
and (case WHEN c.dist_version_id IS NULL THEN c.UCS_prod_no
ELSE
CASE
WHEN isnull(pt.version_control_ind, 'N') = 'Y' THEN xref.rss_prod_no
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NULL AND
xref.rss_film_id IS NULL THEN xref.rss_titleid
WHEN
isnull(pt.version_control_ind, 'N') = 'N' AND
xref.rss_prod_no IS NOT NULL AND
xref.rss_film_id IS NULL THEN substring(pc.glacct, 24, 5) -- ASR 3290687
WHEN isnull(pt.version_control_ind, 'N') = 'N' AND xref.rss_film_id IS NOT NULL THEN isnull(substring(pc.glacct, 24, 5), -- ASR 3290687
(
SELECT substring(dbo.ert_product.glacct, 24, 5) -- ASR 3290687
FROM dbo.ert_product
WHERE dbo.ert_product.product_id = a.parent_product_id
))
END
END in (select prod_no from #prod_no) or #prod_no = 0)

How to append CTE results to main query output?

I've created a TSQL query that pulls from two sets of tables in my database. The tables in the Common Table Expression are different from the tables in the main query. I'm joining on MRN and need the end result to contain accounts from both sets of tables. I've written the following query to this end:
with cteHosp as(
select Distinct p.EncounterNumber, p.MRN, p.AdmitAge
from HospitalPatients p
inner join Eligibility e on p.MRN = e.MRN
inner join HospChgDtl c on p.pt_id = c.pt_id
inner join HospitalDiagnoses d on p.pt_id = d.pt_id
where p.AdmitAge >=12
and d.dx_cd in ('G89.4','R52.1','R52.2','Z00.129')
)
Select Distinct a.AccountNo, a.dob, DATEDIFF(yy, a.dob, GETDATE()) as Age
from RHCCPTDetail c
inner join RHCAppointments a on c.ClaimID = a.ClaimID
inner join Eligibility e on c.hl7Id = e.MRN
full outer join cteHosp on e.MRN = cteHosp.MRN
where DATEDIFF(yy, a.dob, getdate()) >= 12
and left(c.PriDiag,7) in ('G89.4','R52.1','R52.2', 'Z00.129')
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode2,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode3,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
or (
DATEDIFF(yy, a.dob, getdate()) >= 12
and LEFT(c.DiagCode4,7) in ('G89.4','R52.1','R52.2','Z00.129')
)
order by AccountNo
How do I merge together the output of both the common table expression and the main query into one set of results?
Merge performs inserts, updates or deletes. I believe you want to join the cte. If so, here is an example.
Notice the cteBatch is joined to the Main query below.
with
cteBatch (BatchID,BatchDate,Creator,LogID)
as
(
select
BatchID
,dateadd(day,right(BatchID,3) -1,
cast(cast(left(BatchID,4) as varchar(4))
+ '-01-01' as date)) BatchDate
,Creator
,LogID
from tblPriceMatrixBatch b
unpivot
(
LogID
for Logs in (LogIDISI,LogIDTG,LogIDWeb)
)u
)
Select
0 as isCurrent
,i.InterfaceID
,i.InterfaceName
,b.BatchID
,b.BatchDate
,case when isdate(l.start) = 0 and isdate(l.[end]) = 0 then 'Scheduled'
when isdate(l.start) = 1 and isdate(l.[end]) = 0 then 'Running'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) = 1 then 'Failed'
when isdate(l.start) = 1 and isdate(l.[end]) = 1 and isnull(l.haserror,0) != 1 then 'Success'
else 'idunno' end as stat
,l.Start as StartTime
,l.[end] as CompleteTime
,b.Creator as Usr
from EOCSupport.dbo.Interfaces i
join EOCSupport.dbo.Logs l
on i.InterfaceID = l.InterfaceID
join cteBatch b
on b.logid = l.LogID

How to PIVOT this query and display only TOP 10 records filtered by SUM(NetWrittenPremium) DESC

In this query I cant understand what would be the proper syntax to PIVOT it by month and also display just top 10 records based on SUM(NetWrittenPremium).
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT
--TOP 10
RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL
ORDER BY NetWrittenPremium DESC,YearNum,MonthNum
The result should look something like that:
If I use the query below and then using matrics in SSRS to PIVOT it - then after grouping by Description it only displays me 2 Description.
;with cte_TopClasses
AS (
select
b.YearNum,
b.MonthNum,
REPLACE(ClassCode,'+','') + ' - '+ QLL.Description as Description,
SUM( Premium) as NetWrittenPremium
FROM tblCalendar b
LEFT JOIN ProductionReportMetrics prm ON b.MonthNum=Month(prm.EffectiveDate) AND b.YearNum = YEAR(EffectiveDate)
AND prm.EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND prm.EffectiveDate <= EOMONTH(GETDATE()) AND CompanyLine = 'Ironshore Insurance Company'
LEFT JOIN NetRate_Quote_Insur_Quote Q ON prm.NetRate_QuoteID = Q.QuoteID
LEFT JOIN NetRate_Quote_Insur_Quote_Locat QL ON Q.QuoteID = QL.QuoteID
LEFT JOIN (SELECT * FROM NetRate_Quote_Insur_Quote_Locat_Liabi nqI
JOIN ( SELECT LocationID as LocID, MAX(ClassCode) as ClCode
FROM NetRate_Quote_Insur_Quote_Locat_Liabi GROUP BY LocationID ) nqA
ON nqA.LocID = nqI.LocationID AND nqA.ClCode = nqI.ClassCode ) QLL
ON QLL.LocationID = QL.LocationID
WHERE ( b.YearNum = YEAR(GETDATE())-1 and b.MonthNum >= MONTH(GETDATE())+1 ) OR
( b.YearNum = YEAR(GETDATE()) and b.MonthNum <= MONTH(GETDATE()) )
GROUP BY b.YearNum,b.MonthNum,ClassCode, QLL.Description
)
SELECT *
FROM (SELECT RANK() OVER (ORDER BY NetWrittenPremium DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IS NOT NULL) AA
WHERE AA.Rank <= 10
ORDER BY AA.NetWrittenPremium DESC, AA.YearNum, AA.MonthNum
And the result of it in SSRS matrics :
You could try something like this at the end of the query, rather than what is there now:
SELECT *
FROM (SELECT RANK() OVER (ORDER BY [Description] DESC) AS Rank, *
FROM cte_TopClasses
WHERE Description IN (SELECT [Description]
FROM (SELECT RANK() OVER (ORDER BY SUM(NetWrittenPremium) DESC) AS [Rank], [Description], SUM(NetWrittenPremium) AS total
FROM cte_TopClasses
WHERE [Description] IS NOT NULL
GROUP BY [Description]) BB
WHERE [Rank] <= 10)) AA
ORDER BY YearNum, MonthNum
This wraps the query in a SELECT, and filters the ranked results to the 10 you want.
Then use a matrix in the report to pivot the results.

How do I get the max from a partitioned query using Rank ()

I want the result to return the max Rank when partitioned using the rank function.
I am using the following query.
SELECT DISTINCT dbo.pomst.co_num
,dbo.pomst.wh_num
,dbo.pomst.po_number
,dbo.pomst.po_suffix
,dbo.pomst.vendor_id
,dbo.item.uom
,dbo.item.upc_num
,dbo.item.item_desc
,RIGHT(dbo.auditlog.pallet_id, 8) AS pallet_id
,dbo.auditlog.abs_num
,dbo.auditlog.item_qty
,dbo.auditlog.lot
,dbo.auditlog.packer
,auditlog.comments
,auditlog.date_time
,rank() OVER (
PARTITION BY auditlog.comments ORDER BY auditlog.date_time ASC
) AS CorrectTrans
FROM dbo.auditlog
INNER JOIN dbo.pomst ON dbo.auditlog.co_num = dbo.pomst.co_num
AND dbo.auditlog.wh_num = dbo.pomst.wh_num
AND dbo.auditlog.po_number = dbo.pomst.po_number
AND dbo.auditlog.po_suffix = dbo.pomst.po_suffix
INNER JOIN dbo.item ON dbo.auditlog.co_num = dbo.item.co_num
AND dbo.auditlog.wh_num = dbo.item.wh_num
AND dbo.auditlog.abs_num = dbo.item.abs_num
WHERE (dbo.pomst.co_num = 'AC01')
AND (dbo.pomst.wh_num = 'KU22')
AND (dbo.pomst.row_status = 'C')
AND (dbo.auditlog.trans_type = 're')
AND item_qty NOT LIKE '-%'
I figured it out! I was trying to get the max result of a rank, but if I flip order of rank from asc to desc and use a CTE I can select the the results that always have 1 as the rank as opposed to trying to get the Max. I would still like to know how to get the Max rank but this solution suits my needs.
;with cte as
(SELECT DISTINCT dbo.pomst.co_num
,dbo.pomst.wh_num
,dbo.pomst.po_number
,dbo.pomst.po_suffix
,dbo.pomst.vendor_id
,dbo.item.uom
,dbo.item.upc_num
,dbo.item.item_desc
,RIGHT(dbo.auditlog.pallet_id, 8) AS pallet_id
,dbo.auditlog.abs_num
,dbo.auditlog.item_qty
,dbo.auditlog.lot
,dbo.auditlog.packer
,auditlog.comments
,auditlog.date_time
,rank() OVER (
PARTITION BY auditlog.comments ORDER BY auditlog.date_time desc
) AS CorrectTrans
FROM dbo.auditlog
INNER JOIN dbo.pomst ON dbo.auditlog.co_num = dbo.pomst.co_num
AND dbo.auditlog.wh_num = dbo.pomst.wh_num
AND dbo.auditlog.po_number = dbo.pomst.po_number
AND dbo.auditlog.po_suffix = dbo.pomst.po_suffix
INNER JOIN dbo.item ON dbo.auditlog.co_num = dbo.item.co_num
AND dbo.auditlog.wh_num = dbo.item.wh_num
AND dbo.auditlog.abs_num = dbo.item.abs_num
WHERE (dbo.pomst.co_num = 'AC01')
AND (dbo.pomst.wh_num = 'KU22')
AND (dbo.pomst.row_status = 'C')
AND (dbo.auditlog.trans_type = 're')
AND item_qty NOT LIKE '-%'
)
Select * from cte
where CorrectTrans = 1
Add select and group by and use your existing query as a sub query.
Try ..
select max([CorrectTrans]), Vendor_Id, Item_qty, Lot, Pallet_id
from (
-- Your existing query --
SELECT DISTINCT dbo.pomst.co_num
,dbo.pomst.wh_num
,dbo.pomst.po_number
,dbo.pomst.po_suffix
,dbo.pomst.vendor_id
,dbo.item.uom
,dbo.item.upc_num
,dbo.item.item_desc
,RIGHT(dbo.auditlog.pallet_id, 8) AS pallet_id
,dbo.auditlog.abs_num
,dbo.auditlog.item_qty
,dbo.auditlog.lot
,dbo.auditlog.packer
,auditlog.comments
,auditlog.date_time
,rank() OVER (
PARTITION BY auditlog.comments ORDER BY auditlog.date_time ASC
) AS CorrectTrans
FROM dbo.auditlog
INNER JOIN dbo.pomst ON dbo.auditlog.co_num = dbo.pomst.co_num
AND dbo.auditlog.wh_num = dbo.pomst.wh_num
AND dbo.auditlog.po_number = dbo.pomst.po_number
AND dbo.auditlog.po_suffix = dbo.pomst.po_suffix
INNER JOIN dbo.item ON dbo.auditlog.co_num = dbo.item.co_num
AND dbo.auditlog.wh_num = dbo.item.wh_num
AND dbo.auditlog.abs_num = dbo.item.abs_num
WHERE (dbo.pomst.co_num = 'AC01')
AND (dbo.pomst.wh_num = 'KU22')
AND (dbo.pomst.row_status = 'C')
AND (dbo.auditlog.trans_type = 're')
AND item_qty NOT LIKE '-%'
-- =======================================
) x
group by Vendor_id, Item_qty, Lot, Pallet_id