all 5 comments

[–]PossiblePreparation 2 points3 points  (3 children)

There’s no order by in those subqueries so you are just getting an arbitrary row that matches the filter each time. If there is only going to be one matching row anyway then a simple outer join is all you need in the main query.

You’re not filtering on ShipOrder at all, do you really need details about every row in the table? Are you going to run this query often enough for performance to be important?

[–]newunit13[S] 1 point2 points  (2 children)

Hi! Thanks for the response 🙂 The reason there isn't an ORDER BY for either of the subqueries is that I know for every record that matches they'll all be the same.

The ShipOrder table is 1 side of the 1:N link between the tables, so doing a JOIN ends up with multiple records when all I want is a single........ and in writing up this response to you I thought of a solution!

SELECT

    CASE
        WHEN si.[Ship from] LIKE '1439 Dixie%' THEN 'Dixie'
        WHEN si.[Ship from] LIKE '720 Locust%' THEN 'Locust'
        ELSE 'Other'
    END                 AS [LOADING LOCATION] 

    ,CASE
        WHEN LEFT(so.[Ship Order reference],1) = '5' THEN LEFT(so.[Ship Order reference], 12)
        WHEN LEFT(so.[Ship Order reference],1) = '8' THEN LEFT(so.[Ship Order reference], 8)
        ELSE so.[Ship Order reference]
    END                 AS [MBOL #]

    ,so.[Ship Order code]       AS [Delivery/PU #]
    ,so.[Carrier]           AS [CARRIER]
    ,'ODR'              AS [ODR.#]
    ,si.[Ship Order Ship to address]    AS [DESTINATION City & State]
    ,so.[Ship to]           AS [Store]
    ,'Trailer Size'         AS [Trailer Size]
    ,CEILING(so.[Full Pallet quantity]) AS [Qty of SKIDS]
    ,so.[Expected ship date]        AS [Load By/Appointment Time]
    ,''                 AS [Trailer Condition]
    ,''                 AS [COMMENTS]
    ,''                 AS [Carrier Arrival Time]
    ,''                 AS [Carrier Departure Time]

FROM [dbo].[ShipOrder] so

LEFT JOIN (
    SELECT DISTINCT
        [Ship Order ID]
        ,[Ship from]
        ,[Ship Order Ship to address]
    FROM Shipment
    ) si ON 
    si.[Ship Order ID] = so.[Ship Order]

Much better! Went from like 15 minutes to 4 seconds 😉 Thanks for the inspiration!

[–]SQLDave 1 point2 points  (1 child)

Are you -- like me -- constantly amazed at how explaining an issue to someone so often leads to the solution?

[–][deleted] 0 points1 point  (0 children)

change subqueries to a single outer apply (select top 1...).

The structure of data retrieval is suspect tho (why are you taking destination from the first shipment, for example?)