tmajor99
asked on
SQL Select - Grouping Rows
I need help with a SQL Select Script that will remove duplicates and combine values. I have a table with two columns. Right now each ID is duplicated by the validity. I just need need to combine all validity values and separate by a ";".
ID Validity
------ -----------
12A Product
12A Family
12A FO
31C Product
87A FO
87A Product
Expected Output:
ID Validity
------ -----------
12A Product; Family;FO
31C Product
87A FO; Product
ID Validity
------ -----------
12A Product
12A Family
12A FO
31C Product
87A FO
87A Product
Expected Output:
ID Validity
------ -----------
12A Product; Family;FO
31C Product
87A FO; Product
Have a look at this thread: GROUP BY to combine/concat a column.
What database system are you using ? Every system has its' own flavor of SQL. I can cook something for you quick, but I am not sure we are using the same system.
tmajor99
I notice you have asked questions on Oracle and SQL Server in the past, and the way those 2 products do what you want are radically different. PLEASE always indicate what database you want the query for.
ORACLE
MS SQL Server
MySQL
I notice you have asked questions on Oracle and SQL Server in the past, and the way those 2 products do what you want are radically different. PLEASE always indicate what database you want the query for.
ORACLE
select id, listagg(validity,';') within group (order by validity) as validity
from table1
group by id
order by id
MS SQL Server
select
id, ca.validity
from table1 t1
cross apply (
SELECT
STUFF((
SELECT
';' + validity
FROM table1 t2
WHERE t1.id = t2.id
ORDER BY validity
FOR XML PATH ('')
)
, 1, 1, '')
) ca (validity)
group by
id, ca.validity
MySQL
select id, group_concat(validity ORDER BY validity SEPARATOR ';') as validity
from table1
group by id
order by id
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
why not ordered? please provide a reason i you making such a statement.
If Order BY is added you will get
12A Family; FO; Product
But requirement is this
12A Product; Family; FO
12A Family; FO; Product
But requirement is this
12A Product; Family; FO
then, it would have been more correct to say: "if you wish to have an un-ordered list do not use order by"
(it reads like an instruction that should always be obeyed, and of course that isn't true)
all 3 of my examples assume the opposite, that tmajor99 would wish to have an ordered list.
(it reads like an instruction that should always be obeyed, and of course that isn't true)
all 3 of my examples assume the opposite, that tmajor99 would wish to have an ordered list.
Yes the ideal way is to use ORDER BY ( ASC/DESC ) but this is a different case.
ASKER
Really nice!