我有一个类似于的表
ID [Int] | Group [Int] | Material [Char(100)]
1 | 1 | wood
2 | 1 | plastic
3 | 1 | iron
4 | 2 | rubber
如何获得输出结果为:
Group | Material
1 | wood/plastic/iron
2 | rubber
附言:火鸟2.5.1
我试过版本:
SELECT Group1, SUM(Material)
FROM Table1
GROUP BY Group1
转换错误
SELECT T1.Group1,
( SELECT Material + ','
FROM Table1 T2
WHERE T2.Group1 = T1.Group1
FOR XML PATH('')
) AS Material
FROM Table1 as T1
GROUP BY T1.Group1
的未知令牌
这可以通过聚合函数LIST()
:来完成
此函数的语法为:
LIST ([ALL | DISTINCT] expression [, separator])
所以对于你的问题:
SELECT "Group", LIST(Material, '/') AS Material
GROUP BY "Group"
注意,由于Group
是一个保留字,因此需要对其进行引用。LIST
的阶数不是确定性的;有时您可以通过使用subselect排序或使用DISTINCT
来强制执行它,但这并不能保证行为。
String lines[] == //each line of your input is as a separate array element
Map<String,List<String>> groupMap = new HashMap<String,List<String>>();
for(String line : lines){
String[] tokens = line.split("|");
String group = tokens[1].trim();
String material = token[2].trim();
if(!groupMap.containsKey(group)){
List<String> values = new ArrayList<String>();
groupMap.put(group, values);
}
groupMap.get(group).add(material));
}
//now we have grouped all the materials. print it
//print headers group | material
for(String key : groupMap.keySet()){
// import org.apache.commons.lang3.StringUtils;
System.out.println(key + "|" + StringUtils.join(groupMap.get(key), "/");
}