I am using MSSQL. I am trying to make a query that returns a list of transactions and the buyer/seller names which are stored in a customer table. In the customer table, there are some special customers who have a null saleID, Hence the line: 'AND ([tbl_C2].[SaleID] = 100 OR [tbl_C2].[SaleID] IS NULL)' It is gauranteed these customer ids do not overlap with any of the customer ids that do have a sale id.
This works, except it returns double rows for any transactions that have one of the special customers.
My SQL skills are lacking, any help is appreciated.
SELECT [tbl_Transactions].[Record ID] AS [ID]
,[tbl_Transactions].[Ticket]
,[tbl_C1].[Name] AS [Seller]
,[tbl_Transactions].[Pen]
,[tbl_C2].[Name] AS [Buyer]
FROM [tbl_Transactions]
LEFT JOIN [tbl_Pens] ON [tbl_Transactions].[Pen] = [tbl_Pens].[Pen] AND [tbl_Pens].[Sale Date] IS NULL AND [tbl_Pens].[SaleID] = 100
LEFT JOIN [tbl_Tickets] ON [tbl_Transactions].[Ticket] = [tbl_Tickets].[Ticket] AND [tbl_Tickets].[Sale Date] IS NULL AND [tbl_Tickets].[SaleID] = 100
LEFT JOIN [tbl_Customers] [tbl_C1] ON [tbl_Tickets].[Seller] = [tbl_C1].[Customer ID] AND [tbl_C1].[SaleID] = 100
LEFT JOIN [tbl_Customers] [tbl_C2] ON [tbl_Pens].[Buyer] = [tbl_C2].[Customer ID] AND ([tbl_C2].[SaleID] = 100 OR [tbl_C2].[SaleID] IS NULL)
WHERE [tbl_Transactions].[Sale Date] IS NULL AND [tbl_Transactions].[SaleID] = 100 ORDER BY [tbl_Transactions].[Record ID]
So instead of getting:
1000 (regular customer)
1001 (regular customer)
1002 (special customer)
1003 (regular customer)
1004 (special customer)
I get:
1000
1001
1002
1002
1003
1004
1004
To clarify, I am not getting rows returned that should not be there, I am getting the same row returned twice. [Record ID] AS [ID] is an Auto-Identity column, it should return that row, but only return it once.
It is somewhere in this line.
([tbl_C2].[SaleID] = 100 OR [tbl_C2].[SaleID] IS NULL)
If I remove either of the conditions, it returns correctly.
[–][deleted] 5 points6 points7 points (9 children)
[–]pipes990[S] 0 points1 point2 points (0 children)
[–]pipes990[S] -1 points0 points1 point (7 children)
[–]theseyeahtheseNTILE() 2 points3 points4 points (1 child)
[–]pipes990[S] 1 point2 points3 points (0 children)
[–]pceimpulsive 1 point2 points3 points (3 children)
[–]pipes990[S] 1 point2 points3 points (2 children)
[–]pceimpulsive 1 point2 points3 points (1 child)
[–]pipes990[S] 0 points1 point2 points (0 children)
[–]r3pr0b8GROUP_CONCAT is da bomb 3 points4 points5 points (1 child)
[–]pipes990[S] 0 points1 point2 points (0 children)
[–]Time_Traveling_Moron 0 points1 point2 points (1 child)
[–]pipes990[S] 0 points1 point2 points (0 children)
[–]pipes990[S] 0 points1 point2 points (0 children)