OK, I'm an advanced newbie at SQL, with enough knowledge to be dangerous.
I have pulled a set of data with a main query, and I need to exclude a subset of records from it. The main query:
`SELECT
[FundID]
,[AssetID]
,[TransactionTypeCode]
,[TradeDate]
,[NetAmountBase]
,[BrokerNumber]
,[TradeID]
,[TradeIDCancel]
FROM [DailyTradeTransactions] WITH (NOLOCK)
WHERE TransactionTypeCode IN ('SELL','CSELL')
AND TradeDate BETWEEN @StartDate AND @EndDate
AND BrokerNumber NOT IN ('12345','23456','34567','45678','56789','67891')`
This returns 382 records. I now have to eliminate all the cancelled sales, so I have a query that returns all the sales that were initiated (identified by 'SELL') and then cancelled by a reversing transaction (identified by 'CSELL'):
``SELECT TradeID ,TradeIDCancel
FROM [DailyTradeTransactions] WITH (NOLOCK)
WHERE TransactionTypeCode IN ('SELL','CSELL')
AND TradeIDCancel Is Not Null
AND TradeDate BETWEEN '4/1/2023' AND '4/7/2023'
AND BrokerNumber NOT IN ('12345','23456','34567','45678','56789','67891')``
This produces a table of 22 records, which consists of 22 TradeIDs with the corresponding 22 TradeIDCancels, which identify the 44 records that need to be excluded. The variables in the TradeIDCancel appear in the TradeID column, since the TradeIDCancel column just identifies which record reversed the corresponding TradeID. That's why I can't just exclude records with "TradeIDCancel Is Not Null" because it'll return the original cancelled trades as if they weren't cancelled.
I tried making the second query a subquery and using NOT EXISTS, but that returns no records, because every transaction has a TradeID.
It's embarrassing that I can't figure it out, but how can I exclude these 44 records?
I'm expecting 338 records, all with NULL in TradeIDCancel.
The 44 that need to be eliminated will consist of 22 records with TradeIDs and NULL in the corresponding TradeIDCancel column, and 22 records with their own TradeIDs, and the TradeIDs of the first 22 records in the corresponding TradeIDCancel column.
All help is greatly appreciated! `
You need to refer to the subquery twice, so create a CTE to do that without executing it twice, plus make the whole query more readable: