Home > Software design >  Unique SQL Query based on Duplicate Values Across Columns
Unique SQL Query based on Duplicate Values Across Columns

Time:12-21

I would look like to build a SQL query that follows the below: I have a table such as:

TransactionID Consumer Producer Outsider TransactionDate
1 Sam Nick Nick 12-01
2 Jack Bob Steve 12-01
3 Jill Jill Aaron 12-02
4 Mike Nancy Mike 12-03
5 Jill Fred Jason 12-04

Based on the role type, I want to check if that person has any other role in another column and output a unique role name. A person can have a different role on a different transaction date. The persons role should not be repeated for the same TransactionID/Date. Example Output:

PersonName UniqueRole TransactionDate
Sam Consumer 12-01
Jack Consumer 12-01
Jill Consumer-Producer 12-02
Mike Consumer-Outsider 12-03
Jill Consumer 12-04
Nick Producer-Outsider 12-01
Bob Producer 12-01
Nancy Producer 12-03
Fred Producer 12-04
Steve Outsider 12-01
Aaron Outsider 12-02
Jason Outsider 12-04

CodePudding user response:

You can do it by first unrolling your three fields "Consumer", "Producer" and "Outsider" into one single field, distinctively per field. Then apply string aggregation with STRING_AGG for each date and person.

WITH cte AS (
    SELECT DISTINCT consumer AS PersonName, 
                    'Consumer' AS UniqueRole, 
                    TransactionDate
    FROM tab
    UNION ALL
    SELECT DISTINCT producer AS PersonName, 
                    'Producer' AS UniqueRole, 
                    TransactionDate
    FROM tab
    UNION ALL
    SELECT DISTINCT outsider AS PersonName, 
                    'Outsider' AS UniqueRole,
                    TransactionDate
    FROM tab
)
SELECT PersonName, 
       STRING_AGG(UniqueRole, '-') AS UniqueRole,
       TransactionDate 
FROM cte
GROUP BY PersonName, TransactionDate
ORDER BY UniqueRole

Check the demo here.

  • Related