Here is a cleaned-up and optimized version of your SQL query. I’ve eliminated redundancies and improved formatting for better readability while preserving the functionality.
DECLARE
@PO_DATE_FROM date = '2024-09-08',
@PO_DATE_TO date = '2024-09-09';
-- The request
WITH DocumentSummary AS (
SELECT
EDITransactionType AS [EDI Doc. Type],
EDIDirection AS [Direction],
TRIM(REPLACE(EDIReference, '-', '')) AS [Doc. Reference (PO, Invoice Nb, ...)],
PartnerID,
PartnerISAId AS [Cust. GS Id],
COUNT(DISTINCT t.ProcessName) AS NbConfirmations,
CONVERT(date, d.InsertTimestamp) AS [Timestamp]
FROM
EDIAudit.Reconciliation.Documents d WITH (NOLOCK)
INNER JOIN
EDIAudit.Reconciliation.DocumentsTransaction t WITH (NOLOCK)
ON t.DocumentPKey = d.DocumentPKey
WHERE
EDITransactionType = 850
AND EDIDirection = 'inbound'
AND CurrentStatus != 'MANUALLY_CONFIRMED'
AND CONVERT(date, d.InsertTimestamp) BETWEEN @PO_DATE_FROM AND @PO_DATE_TO
GROUP BY
EDITransactionType,
EDIDirection,
TRIM(REPLACE(EDIReference, '-', '')),
PartnerID,
PartnerISAId,
CONVERT(date, d.InsertTimestamp)
)
SELECT
ds.[EDI Doc. Type],
ds.Direction,
ds.[Doc. Reference (PO, Invoice Nb, ...)],
ds.PartnerID,
ds.[Cust. GS Id],
ds.[Timestamp],
CASE ds.NbConfirmations
WHEN 1 THEN 'B2Bi'
WHEN 2 THEN 'PyEDI'
ELSE 'COMPASS'
END AS [Last Successful Step]
FROM
DocumentSummary ds
WHERE
ds.NbConfirmations < 3
UNION
SELECT
ds.[EDI Doc. Type],
ds.Direction,
ds.[Doc. Reference (PO, Invoice Nb, ...)],
ds.PartnerID,
ds.[Cust. GS Id],
ds.[Timestamp],
CASE ds.NbConfirmations
WHEN 1 THEN 'B2Bi'
WHEN 2 THEN 'PyEDI'
ELSE 'COMPASS'
END AS [Last Successful Step]
FROM
DocumentSummary ds
WHERE
ds.NbConfirmations = 3
AND EXISTS (
SELECT 1
FROM EDIAudit.Reconciliation.Documents d
WHERE d.CurrentStatus = 'RECEIVED'
AND CONVERT(date, d.InsertTimestamp) BETWEEN @PO_DATE_FROM AND @PO_DATE_TO
)
ORDER BY
ds.[Timestamp], ds.PartnerID, ds.[Doc. Reference (PO, Invoice Nb, ...)];
Key Improvements:
- Common Table Expression (CTE): A
WITH
clause was used to reduce redundancy in yourSELECT
statements. The logic for countingNbConfirmations
and formatting columns is now centralized. - Eliminated Redundant Queries: The core query logic has been reduced, and differences in conditions (
NbConfirmations < 3
or= 3
) are applied via filtering after the CTE. - Improved Readability: The code is more organized, making it easier to maintain and understand.
Let me know if you need any further adjustments!