Pergunta

I have a table like:

ID [Int] | Group [Int] | Material [Char(100)]
1        | 1           | wood
2        | 1           | plastic
3        | 1           | iron
4        | 2           | rubber

How to get an output result as:

Group | Material
1     | wood/plastic/iron
2     | rubber

P.S.: Firebird 2.5.1

I had tried versions:

SELECT Group1, SUM(Material)
FROM Table1
GROUP BY Group1

convert error

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

unknown token FOR

Foi útil?

Solução

This can be done with the aggregate function LIST():

This function has the syntax:

LIST ([ALL | DISTINCT] expression [, separator])

So for your problem:

SELECT "Group", LIST(Material, '/') AS Material
GROUP BY "Group"

Note that as Group is a reserved word, it needs to be quoted. The order of LIST is not deterministic; sometimes you can enforce it by sorting with a subselect or by using DISTINCT, but this is not guaranteed behavior.

Outras dicas

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), "/");
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top