简体   繁体   中英

Get the last record in each group with sum/count

There is a table table1 that contains data as shown below: code & amount is fields of table1.

I want to generate of report from records from table1 with group by each code and also get sum of each code, as shown below

在此处输入图像描述

Any idea about how to generate an output like above? For Java development

You're really looking for 2 sets of results here. The individual row output and the group by output require 2 separate queries.

You could

SELECT code, amount
FROM table1
ORDER BY code

for the individual amounts, and

SELECT code, sum(amount)
FROM table1
GROUP BY code

for the sums.

Personally I'd rather avoid making a second query. Just use the first query and do the summing/formatting from within my Java code.

You can collect a map from this table and group duplicates into a list . Then to represent data you can iterate over this map and get the sum of each list.

Example of output to the markdown table:

String[][] table = {
        {"aaa", "10"},
        {"aaa", "5"},
        {"aaa", "20"},
        {"bbb", "30"},
        {"bbb", "5"},
        {"ccc", "40"}};
Map<String, List<Integer>> map = Arrays.stream(table)
        .collect(Collectors.toMap(
                arr -> arr[0],
                arr -> new ArrayList<>(List.of(Integer.parseInt(arr[1]))),
                (list1, list2) -> {
                    list1.addAll(list2);
                    return list1;
                }, TreeMap::new));
// raw output
System.out.println(map);
// {aaa=[10, 5, 20], bbb=[30, 5], ccc=[40]}
// output to the markdown table
map.forEach((key, value) -> {
    System.out.println("| code | amount |");
    System.out.println("|---|---|");
    value.forEach(element ->
            System.out.println("| " + key + " | " + element + " |"));
    System.out.println("| <b>Sum</b> | <b>" + value.stream()
            .mapToInt(Integer::intValue).sum() + "</b> |");
    System.out.println();
});
code amount
aaa 10
aaa 5
aaa 20
code amount
bbb 30
bbb 5
code amount
ccc 40

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM