Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid duplicate records while retrieving using Inner Join in SQL Server

Here is my Store Procedure for printing purpose. I am facing issue as i get records twice as they exist due to commented join. I want to get output as mentioned below in question. I am a novice to DB. Help in this regard will be appreciated.

DECLARE @path AS VARCHAR(100)
SET @path = N'~/BillAttachments/166/'
DECLARE @billID AS INT
SET @billID = 166

SELECT bh.billID,bh.statusID,bh.modifiedOn,bs.statusName
FROM dbo.eInvoice_tbl_billHistory AS bh
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON bh.billID = ba.billID
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON ba.billID = bh.billID
INNER JOIN dbo.eInvoice_tbl_billStatus AS bs ON bh.statusID = bs.statusID
WHERE bh.billID=@billID;

when i try to fetch these columns from the required tables

ba.attachmentID ,
        @path + ba.fileName AS asad ,
        ba.attachmentDescription ,
        ba.billAttachmentStatus,

Output is:

166 3   2015-11-30 11:44:18.663 Approve
166 3   2015-11-30 11:44:18.663 Approve
166 5   2015-11-30 11:44:42.600 Paid
166 5   2015-11-30 11:44:42.600 Paid

but desired output is:

166 3   2015-11-30 11:44:18.663 Approve
166 5   2015-11-30 11:44:42.600 Paid
like image 201
Billing Systems Avatar asked May 11 '26 18:05

Billing Systems


1 Answers

Use DISTINCT:

Specifies that only unique rows can appear in the result set

SELECT DISTINCT bh.billID,bh.statusID,bh.modifiedOn,bs.statusName 
FROM dbo.eInvoice_tbl_billHistory AS bh
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON bh.billID = ba.billID
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON ba.billID = bh.billID
INNER JOIN dbo.eInvoice_tbl_billStatus AS bs ON bh.statusID = bs.statusID
WHERE bh.billID=@billID;

Other method is to use GROUP BY:

SELECT bh.billID,bh.statusID,bh.modifiedOn,bs.statusName 
FROM dbo.eInvoice_tbl_billHistory AS bh
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON bh.billID = ba.billID
--INNER JOIN dbo.eInvoice_tbl_billAttachment AS ba ON ba.billID = bh.billID
INNER JOIN dbo.eInvoice_tbl_billStatus AS bs ON bh.statusID = bs.statusID
WHERE bh.billID=@billID
GROUP BY bh.billID,bh.statusID,bh.modifiedOn,bs.statusName;
like image 191
Lukasz Szozda Avatar answered May 14 '26 08:05

Lukasz Szozda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!