Отображать только более одного уникального клиента / адрес на номер грузовика - PullRequest
0 голосов
/ 28 апреля 2020

Работал над проектом, в котором отчет будет сгенерирован из запроса SQL. sh для отображения всех отправлений (на основе уникальных автоматов c идентификатор грузовика), которые содержат любую комбинацию:

  • уникальных клиентов (на основе номера клиента, более одного номера клиента на одну отправку) )
  • Уникальные адреса (на основе определенного поля адреса, более одного уникального адреса на одну отправку)

Вывод должен выглядеть следующим образом, если код работает правильно:

Truck  Customer First Address         (other addresses)    City      State  ZIP  Country
12345  C12345   567 Hummingbird Lane                       Detroit    MI   48610   US
12345  C12345   908 Elm Street                             Detroit    MI   48611   US
12345  C78901   219 Maple Street                           Lansing    MI   49012   US

Вот пример кода, который я пытался раскрыть этой информацией:

WITH cte
AS (SELECT DISTINCT shp.shipmentID
                    , ven.CustomerCode
                    , ven.CustomerName
                    , ads.FirstAddress
                    , ads.SecondAddress
                    , ads.ThirdAddress
                    , ads.City
                    , ads.State
                    , ads.Zip
                    , ads.Country
    FROM
           dbo.OrderItems AS ori
           JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
           JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
           JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
           JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
           JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
           JOIN dbo.Address AS ads ON ads.addID = oa.addID
           JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
                                           AND adst.atcAddressTypeCode = N'SHIP'
           JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
                                                   AND ori.itmIDInstance = shpo.itmIDInstance
                                                   AND ori.olnID = shpo.olnID
                                                   AND ori.olnIDInstance = shpo.olnIDInstance
           JOIN dbo.Shipments AS shp ON shp.shipmentID = shpo.shpID
           WHERE shpo.shpID = shp.shipmentID
           AND ven.venCode IS NOT NULL
           )
   , maxadd
AS (SELECT
         aa.venCode
       , MAX(Multadd) AS Multadd
    FROM (
             SELECT
                 ROW_NUMBER() OVER (PARTITION BY cte.shipmentID, cte.CustomerCode ORDER BY cte.shipmentID) Multadd
               , cte.shipmentID
               , cte.CustomerCode
               , cte.CustomerName
               , cte.FirstAddress
               , cte.SecondAddress
               , cte.ThirdAddress
               , cte.City
               , cte.State
               , cte.Zip
               , cte.Country
             FROM
                 cte
         ) AS aa
    GROUP BY
         aa.CustomerCode
         HAVING COUNT (*)>1
         )
   , maxshp
AS (SELECT
         cc.shipmentID
       , MAX(cc.Multadd) AS MultVencode
    FROM (
             SELECT
                  bb.shipmentID
                , bb.CustomerCode
                , ROW_NUMBER() OVER (PARTITION BY shipmentID ORDER BY CustomerCode) Multadd
             FROM (SELECT DISTINCT cte.shipmentID, cte.CustomerCode FROM cte) AS bb
         ) AS cc
    GROUP BY
         cc.shipmentID
    HAVING COUNT(*) > 1
        )
SELECT
    cte.shipmentID
 , cte.CustomerCode
  , cte.CustomerName
  , cte.FirstAddress
  , cte.SecondAddress
  , cte.ThirdAddress
  , cte.City
  , cte.State
  , cte.Zip
  , cte.Country
  , maxadd.Multadd AS AddOnShipID
  , maxshp.MultVencode AS VenOnShipID
FROM
    cte
    JOIN maxadd ON maxadd.CustomerCode = cte.CustomerCode
    JOIN maxshp ON maxshp.shipmentID = cte.shipmentID
WHERE 
    (
        maxadd.Multadd <> 2
        AND maxshp.MultVencode <> 1
    )

ORDER BY
    cte.shipmentID
  , cte.CustomerCode;

Этот «квази» работает. Я ломал голову над тем, почему это все еще не работает. Интересно, может ли второй набор глаз найти что-то, что я пропускаю?

1 Ответ

0 голосов
/ 29 апреля 2020
SELECT * FROM (SELECT DISTINCT shp.shipmentID
                                                       , ven.CustomerCode
                                                       , ven.CustomerName
                                                       , ads.FirstAddress
                                                       , ads.SecondAddress
                                                       , ads.ThirdAddress
                                                       , ads.City
                                                       , ads.State
                                                       , ads.Zip
                                                       , CASE WHEN(ads.Country LIKE 'US') THEN N'USA' ELSE 'CANADA' END AS Country
                                                       , COUNT (shp.shipmentID) OVER (PARTITION BY shipmentID ORDER BY shp.shpID) AS cntshpID


                        FROM dbo.OrderItems AS ori
                        JOIN dbo.OrderLineProducts AS olns ON olns.olnID = ori.olnID
                        JOIN dbo.OrderLines AS oln ON oln.olnID = olns.olnID
                        JOIN dbo.Orders AS ord ON oln.ordID = ord.ordID
                        JOIN dbo.VendorCustomer AS ven ON ven.venID = ord.venID
                        JOIN dbo.OrderAddresses AS oa ON oa.ordID = ord.ordID
                        JOIN dbo.Address AS ads ON ads.addID = oa.addID
                        JOIN dbo.AddressType AS adst ON adst.atcID = ads.atcID
                                                       AND adst.atcAddressTypeCode = N'SHIP'
                        JOIN dbo.OrderItemShipments AS shpo ON ori.itmID = shpo.itmID
                                                       AND ori.itmIDInstance = shpo.itmIDInstance
                                                       AND ori.olnID = shpo.olnID
                                                       AND ori.olnIDInstance = shpo.olnIDInstance
                        JOIN dbo.Shipments AS shp ON shp.shpID = shpo.shipmentID
                        WHERE shpo.shpID = shp.shipmentID

                        GROUP BY shp.shipmentID
                                         , ven.CustomerCode
                                         , ven.CustomerName
                                         , ads.FirstAddress
                                         , ads.SecondAddress
                                         , ads.ThirdAddress
                                         , ads.City
                                         , ads.State
                                         , ads.aZip
                                         , ads.Country) AS bb

WHERE bb.cntshpID > 1

ORDER BY shpID ASC

CTE не был способом к go, он слишком усложнил что-то простое.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...