我有下表Tble:
Name | Level -------------- n1 | L1 n1 | L2 n2 | L1 n2 | L3 n3 | L1 n4 | L3
如何将SQL查询编写为输出?
Name | Level ---------------- n1 | L1_L2 n2 | L1_L3 n3 | L1 n4 | L3
谢谢
答案 0 :(得分:1)
假设MySQL:
SELECT Name, GROUP_CONCAT(Level SEPARATOR "_") Level
FROM tbl
GROUP BY Name
<强>结果强>
| NAME | LEVEL | ---------------- | n1 | L1_L2 | | n2 | L1_L3 | | n3 | L1 | | n4 | L3 |
答案 1 :(得分:1)
所以,如果你的问题标题建议总是2行,那么就这样做:
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
在11g中,如果每个名称超过2行,则可以使用listagg:
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
或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
答案 2 :(得分:0)
这是Oracle 11g R2 解决方案:使用LISTAGG
:
SELECT "Name", LISTAGG("Level", ',') WITHIN GROUP (ORDER BY "Level") "Levels"
FROM Table1
GROUP BY "Name"
ORDER BY "Name";
答案 3 :(得分:0)
HSQLDB支持与MySQL相同的语法,但它使用SQL Standard单引号作为字符串常量。
SELECT "Name", GROUP_CONCAT("Level" ORDER BY "Level" SEPARATOR '_') "Level"
FROM "Tbl"
GROUP BY "Name"
ORDER BY "Name"
此示例假定您有引用的,大小写混合的表和列名称。
http://www.hsqldb.org/doc/2.0/guide/dataaccess-chapt.html#dac_aggregate_funcs