My SQL query joins on multiple tables, and because of this it is displaying multiple results. I know about SELECT DISTINCT, but one of the fields (‘Account.Name’) is occasionally different, so it treats this record as a new row. Any ideas? Here is my SQL:
SELECT DISTINCT
d.ID, ISNULL(d.OnHold, 0) AS 'OnHold', d.OnHoldReason AS 'On Hold Reason', d.LegacyID AS 'Consignment#', d.IntConNo AS 'Consignment Ref',
CASE WHEN JobType = 'O' THEN 'Outward' ELSE 'Collection' END AS 'Job Type', d.TripDate AS 'Delivery Date', d.DeliveryTown AS 'Delivery Town',
d.DeliveryPostcode AS 'Delivery Postcode', d.VehicleReg AS 'Vehicle Reg', d.RequiredCollectionDate AS 'Req. Collection Date',
d.VehicleReg AS 'Vehicle Registration', CASE WHEN d .DeliveryStatus = 2 THEN 'OK' END AS 'Delivery Status', d.ItemsignedBy AS 'POD Signed By',
d.BaseRate AS 'Base Rate', d.FuelSurcharge AS 'Fuel Surcharge', d.AdditionalCharges AS 'Additional Charges',
d.BaseRate + d.FuelSurcharge + d.AdditionalCharges AS 'Value', CASE WHEN InvoiceNumber IS NULL THEN CONVERT(bit, 0) ELSE CONVERT(bit, 1)
END AS Tagged, CASE WHEN di.Total = di.Delivered THEN 'Recieved' ELSE 'Not Recieved' END AS 'Items', Account.Name
FROM Deliveries AS d LEFT OUTER JOIN
(SELECT Consignment, COUNT(*) AS Total, COUNT(CASE WHEN Status = 2 THEN 1 END) AS Delivered
FROM Items
GROUP BY Consignment) AS di ON d.ID = di.Consignment INNER JOIN
Account ON d.Customer = Account.InvoiceAccount
WHERE (d.InvoiceNumber IS NULL) AND (d.TripDate > 29 / 11 / 2010)
ORDER BY 'Consignment#'
The easiest solution would be to replace the DISTINCT with a GROUP BY. The dowside is that only one accountname get’s returned.
Other solutions could be
Using group by