use [test1_AlplaPROD2.0_Read]

DECLARE @StartDate DATE = '[startDate]'
DECLARE @EndDate   DATE = '[endDate]'

;WITH bol_20 AS (   -- 2.0 BOL, one per release (newest doc wins)
    SELECT  pos.ReleaseId,
            dd.JournalNumber,
            ROW_NUMBER() OVER (PARTITION BY pos.ReleaseId
                               ORDER BY dd.ShippingDate DESC) AS rn
    FROM    [outboundDelivery].[DeliveryDocumentPosition] (nolock) pos
    JOIN    [outboundDelivery].[DeliveryDocument]         (nolock) dd
              ON dd.Id = pos.DeliveryDocumentId
    -- WHERE dd.DocumentType = <BOL value>   -- see note below
)
SELECT
      r.[ArticleHumanReadableId]
     ,[ReleaseNumber]
     ,h.CustomerOrderNumber
     ,x.CustomerLineItemNumber
     ,[CustomerReleaseNumber]
     ,[ReleaseState]
     ,[DeliveryState]
     ,COALESCE(ea.JournalNummer, bol_20.JournalNumber) AS BOL_Number   -- 1.0 or 2.0
     ,[ReleaseConfirmationState]
     ,[PlanningState]
      ,format(r.[OrderDate], 'yyyy-MM-dd HH:mm') as OrderDate
      --,r.[OrderDate]
      ,FORMAT(r.[DeliveryDate], 'yyyy-MM-dd HH:mm') as DeliveryDate
      --,r.[DeliveryDate]
      ,FORMAT(r.[LoadingDate], 'yyyy-MM-dd HH:mm') as LoadingDate
      --,r.[LoadingDate]
     ,[Quantity]
     ,[DeliveredQuantity]
     ,r.[AdditionalInformation1]
     ,r.[AdditionalInformation2]
     ,[TradeUnits]
     ,[LoadingUnits]
     ,[Trucks]
     ,[LoadingToleranceType]
     ,[SalesPrice]
     ,[Currency]
     ,[QuantityUnit]
     ,[SalesPriceRemark]
     ,r.[Remark]
     ,[Irradiated]
     ,r.[CreatedByEdi]
     ,[DeliveryAddressHumanReadableId]
     ,DeliveryAddressDescription
     ,[CustomerArtNo]
     ,[TotalPrice]
     ,r.[ArticleAlias]
FROM [order].[Release] (nolock) AS r
LEFT JOIN [order].LineItem AS x ON r.LineItemId = x.id
LEFT JOIN [order].Header   AS h ON x.HeaderId   = h.id

-- 1.0 BOL (legacy) — unchanged
LEFT JOIN AlplaPROD_test1.dbo.V_LadePlanungenLadeAuftragAbruf (nolock) AS zz
       ON zz.AbrufIdAuftragsAbruf = r.ReleaseNumber
LEFT JOIN (
    SELECT * FROM (
        SELECT ROW_NUMBER() OVER (PARTITION BY IdJournal ORDER BY add_date DESC) AS RowNum, *
        FROM [AlplaPROD_test1].[dbo].[T_Lieferungen] (nolock)
    ) t WHERE RowNum = 1
) AS ea ON zz.IdLieferschein = ea.IdJournal

-- 2.0 BOL (new)
LEFT JOIN bol_20 ON bol_20.ReleaseId = r.Id AND bol_20.rn = 1

WHERE r.DeliveryDate BETWEEN @StartDate AND @EndDate
and DeliveredQuantity > 0
--and r.ArticleHumanReadableId in ([articles]) 
--and Journalnummer = 169386