Quantcast
Channel: SCN: Message List
Viewing all articles
Browse latest Browse all 8620

Trying to reduce my results set using a derived table, and an 'outer' select?

$
0
0

Hi Everyone,

 

 

 

I have written a query which shows the last Invoice and Credit associated with a given BP. Here is the code -

 

 

 

SELECT

 

T0.CardCode

 

, ISNULL(CONVERT(nvarchar, MAX(T1.DocDate), 103), '') AS 'Last Transaction'

 

, 'Invoice' AS 'Transaction Type'

 

 

 

FROM OCRD T0

 

LEFT JOIN OINV T1 ON T1.CardCode = T0.CardCode

 

 

 

GROUP BY T0.CardCode

 

 

 

UNION ALL

 

 

 

SELECT

 

T0.CardCode

 

, ISNULL(CONVERT(nvarchar, MAX(T1.DocDate), 103), '') AS 'Last Transaction'

 

, 'Credit' AS 'Transaction Type'

 

 

 

FROM OCRD T0

 

LEFT JOIN ORIN T1 ON T1.CardCode = T0.CardCode

 

 

 

GROUP BY T0.CardCode

 

 

 

ORDER BY CardCode, [Last Transaction]

 

 

 

I have the results that I expect, here is a sample of the results -

 

 

 

Capture.JPG

 

 

 

However I would like to show only the most recent transaction - regardless of whether it is an Invoice or a Credit, as illustrated below -

 

 

 

Capture.JPG

 

 

 

As can be seen above I want to show each CardCode only once, the most recent transaction (either Invoice or Credit), and the Transaction Type.

 

 

 

Towards the above end I modified my original query to the following - however I am still getting the same results as before!

 

 

 

SELECT

 

Tx.CardCode

 

, MAX(Tx.[Last Transaction]) AS 'Last Transaction'

 

, Tx.[Transaction Type]

 

 

 

FROM

 

(

 

    SELECT

 

    T0.CardCode

 

    , ISNULL(CONVERT(nvarchar, MAX(T1.DocDate), 103), '') AS 'Last Transaction'

 

    , 'Invoice' AS 'Transaction Type'

 

 

 

    FROM OCRD T0

 

    LEFT JOIN OINV T1 ON T1.CardCode = T0.CardCode

 

 

 

    GROUP BY T0.CardCode

 

 

 

    UNION ALL

 

 

 

    SELECT

 

    T0.CardCode

 

    , ISNULL(CONVERT(nvarchar, MAX(T1.DocDate), 103), '') AS 'Last Transaction'

 

    , 'Credit' AS 'Transaction Type'

 

 

 

    FROM OCRD T0

 

    LEFT JOIN ORIN T1 ON T1.CardCode = T0.CardCode

 

 

 

    GROUP BY T0.CardCode

 

 

 

) AS Tx

 

 

 

GROUP BY Tx.CardCode, Tx.[Transaction Type]

 

 

 

ORDER BY Tx.CardCode, [Last Transaction]

 

 

 

I thought that by making my original query a derived table, and then on the ('Outer Select') taking the value of MAX(Tx.[Last Transaction]) that I would get the results I desire however this has not been the case.

 

 

 

Any help or suggestions will be greatly appreciated.

 

 

 

Kind Regards,

 

 

 

David


Viewing all articles
Browse latest Browse all 8620

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>