I have the following table Tble :
Name | Level -------------- n1 | L1 n1 | L2 n2 | L1 n2 | L3 n3 | L1 n4 | L3
How can I write a SQL query to output like that ?
Name | Level ---------------- n1 | L1_L2 n2 | L1_L3 n3 | L1 n4 | L3
Thank you
I have the following table Tble :
Name | Level -------------- n1 | L1 n1 | L2 n2 | L1 n2 | L3 n3 | L1 n4 | L3
How can I write a SQL query to output like that ?
Name | Level ---------------- n1 | L1_L2 n2 | L1_L3 n3 | L1 n4 | L3
Thank you
Assuming MySQL:
SELECT Name, GROUP_CONCAT(Level SEPARATOR "_") Level
FROM tbl
GROUP BY Name
Result
| NAME | LEVEL | ---------------- | n1 | L1_L2 | | n2 | L1_L3 | | n3 | L1 | | n4 | L3 |
so if its always 2 rows as your question title suggests, simply do:
SQL> select name,
2 case
3 when min(lvl)=max(lvl) then min(lvl)
4 else min(lvl)||'_'||max(lvl)
5 end lvl
6 from data group by name
7 order by name;
NA LVL
-- -----
n1 L1_L2
n2 L1_L3
n3 L1
n4 L3
in 11g you could use listagg if its more than 2 rows per name:
SQL> select name,
2 listagg(lvl, '_') within group (order by lvl) lvl
3 from data
4 group by name
5 order by name;
NA LVL
-- --------------------
n1 L1_L2
n2 L1_L3
n3 L1
n4 L3
or in 10g:
SQL> select name,
2 replace(wm_concat(lvl), ',', '_') lvl
3 from data
4 group by name
5 order by name;
NA LVL
-- --------------------
n1 L1_L2
n2 L1_L3
n3 L1
n4 L3
Here's Oracle 11g R2 solution: using LISTAGG
:
SELECT "Name", LISTAGG("Level", ',') WITHIN GROUP (ORDER BY "Level") "Levels"
FROM Table1
GROUP BY "Name"
ORDER BY "Name";
HSQLDB supports the same syntax as MySQL, but it uses the SQL Standard single quotes for string constants.
SELECT "Name", GROUP_CONCAT("Level" ORDER BY "Level" SEPARATOR '_') "Level"
FROM "Tbl"
GROUP BY "Name"
ORDER BY "Name"
This example assumes you have quoted, mixed-case table and column names.
http://www.hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs