But I need one unique row for each Header record.
To me it is unclear if you mean one unique record per HT.O_ID
or no duplicate records regarding all the four columns returned.
If it is the latter, add the DISTINCT
keyword to your query (and add the schema names).
SELECT DISTINCT HT.O_ID,
HT.Type,
HT.Total,
IT.Image
FROM dbo.HEADER_TABLE HT
JOIN dbo.LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID
JOIN dbo.IMAGE_TABLE IT
ON IT.Item_ID = LIT.ITEM_ID
WHERE IT.SECTION = 'Retail';
Result
O_ID Type Total Image
1001 Online $10 URL
If that does not solve it
Then you would have to group by the values in the Header_Table
And decide which Image
you need to keep,do concatenation on it, ....
SELECT HT.O_ID,
HT.Type,
HT.Total,
MAX(IT.Image) as MaxURL
FROM dbo.HEADER_TABLE HT
JOIN dbo.LINE_ITEM_TABLE LIT
ON LIT.O_ID = HT.O_ID
JOIN dbo.IMAGE_TABLE IT
ON IT.Item_ID = LIT.ITEM_ID
WHERE IT.SECTION = 'Retail'
GROUP BY HT.O_ID,HT.Type,HT.Total;
Test data
CREATE TABLE dbo.HEADER_TABLE(O_ID int,Type varchar(100),Total varchar(10))
INSERT INTO dbo.HEADER_TABLE(O_ID,Type,Total)
VALUES (1001,'Online','$10');
CREATE TABLE dbo.LINE_ITEM_TABLE(ID int,O_ID int,Item_ID varchar(4),Line_Total varchar(10));
INSERT INTO dbo.LINE_ITEM_TABLE(ID,O_ID,Item_ID,Line_Total)
VALUES (1,1001,'P001','$2'),
(2,1001,'P002','$2'),
(3,1001,'P003','$2'),
(4,1001,'P004','$2'),
(5,1001,'P005','$2');
CREATE TABLE dbo.IMAGE_TABLE(Item_ID varchar(10),Image varchar(100),Section varchar(10))
INSERT INTO dbo.IMAGE_TABLE
VALUES ('P001','URL','Retail'),
('P002','URL','Retail'),
('P003','URL','Stock'),
('P004','URL','Retail'),
('P005','URL','Retail');
on IT.ITEM_ID = LIT.ITEM_ID
. Also, the sample data that you've included doesn't show any duplicates on the ITEM_ID field, so it doesn't look like the query (with the corrected join) would have any duplicates either. Are there actually multiple rows per Item ID in that table?