I have a table in Microsoft Dynamics AX ERP Database of SQL Server 2008 R2, which has some rows, there is a field named qty in table, some rows have negative qty and some rows have positive quantity. There is another field TransactionID, now I want to select all those TransactionIDs which have negative qty, AND also those TransactionIDs which have some rows with positive QTys and negative qtys too.
TransactionID is a foreign key field of a master table.
So far I wrote below code which is not working.
select * from RBOTRANSACTIONSALESTRANS main where main.qty < 0
and main.DATAAREAID = 'DAT'
and exists
(
select 1 from RBOTRANSACTIONSALESTRANS where QTY > 0
and RBOTRANSACTIONSALESTRANS.DATAAREAID = main.DATAAREAID
and RBOTRANSACTIONSALESTRANS.STORE = main.STORE
and RBOTRANSACTIONSALESTRANS.TERMINALID = main.TERMINALID
)
order by main.TRANSACTIONID
A recap, you want to select all rows for which there exists at least one row with the same TransactionID that has a negative quantity?
The main difference is, that you had a
main.QTY < 0check. And I addedsub.TRANSACTIONID = main.TRANSACTIONID.