Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have to write a query to display unique customer comments from the customer table as shown below:

CUSTOMER TABLE

CustomerID	SequenceNo	Comments
1	1	ABC D
1	2	CDE
1	3	ABC
1	4	ABC D
1	5	CDE
1	6	abc
2	7	ABC DEF
2	8	
2	9	ABC DEF
2	10	DEF
2	11	XYZ 123
2	12	ABC
3	13	PQ RST


Definition of above Customer table will be

SQL
CustomerID	INT
SequenceNo	INT
Comments	VARCHAR(MAX)


I want to write a SQL query to filter the records in the Customer Table and display unique comment history for each customer.

Criterias:
1. Display only Unique Comments from Customer Table for all the customers,
2. If Comments are same then display the row which has maximum SequenceNo
3. Comments can be blank.

Output of the about table would be as shown below:

CustomerID	SequenceNo	Comments
1	3	ABC
1	4	ABC D
1	5	CDE
1	6	abc
2	8	
2	9	ABC DEF
2	10	DEF
2	11	XYZ 123
2	12	ABC
3	13	PQ RST


https://www.dropbox.com/s/h0t3xvvvlaqirk3/11698890_10154036087194466_3495075191431781854_o.jpg?dl=0[^]
Posted
Updated 1-Jul-15 11:32am
v3

1 solution

Have a look at sample:

SQL
DECLARE @tmp TABLE(CustomerID   INT, SequenceNo INT, Comments   VARCHAR(MAX))

INSERT INTO @tmp (CustomerID, SequenceNo, Comments)
VALUES(1, 1, 'ABC D'),
(1, 2, 'CDE'),
(1, 3, 'ABC'),
(1, 4, 'ABC D'),
(1, 5, 'CDE'),
(1, 6, 'abc'),
(2, 7, 'ABC DEF'),
(2, 8, NULL),
(2, 9, 'ABC DEF'),
(2, 10, 'DEF'),
(2, 11, 'XYZ 123'),
(2, 12, 'ABC'),
(3, 13, 'PQ RST')

SELECT CustomerID, SequenceNo, Comments
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY CustomerID ORDER BY SequenceNo ASC) AS RowNo
    FROM @tmp
    ) AS T
WHERE RowNo > 1


Above query returns:
CustomerID	SequenceNo	Comments
1	2	CDE
1	3	ABC
1	4	ABC D
1	5	CDE
1	6	abc
2	8	NULL
2	9	ABC DEF
2	10	DEF
2	11	XYZ 123
2	12	ABC
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900