group_by
Group tables using selected columns.
Example
Define columns and table:
#include <cpptables/table.hh>
#include <iostream>
using namespace tables;
using namespace std;
struct c0{ constexpr static string_view name = "Col0"; };
struct c1{ constexpr static string_view name = "Col1"; };
struct c2{ constexpr static string_view name = "Col2"; };
using table_t = table<
pair<c0,string_view>,
pair<c1,unsigned>,
pair<c2,unsigned>
>;
Construct table:
const table_t t0(
{"abc", "def", "ghi", "abc", "def", "ghi","abc", "def", "ghi", "abc", "def", "ghi"},
{1,2,3,4,5,6,7,8,9,10,11,12},
{2,20,200,1,10,100,5,50,500,3,30,300}
);
cout << t0 << "\n";
Output:
Col0 Col1 Col2 -------------- abc 1 2 def 2 20 ghi 3 200 abc 4 1 def 5 10 ghi 6 100 abc 7 5 def 8 50 ghi 9 500 abc 10 3 def 11 30 ghi 12 300
Group by c0
:
using gtable_t = table_t::group_by_t<tuple<c0>>;
const gtable_t g0 = t0.group_by<c0>();
cout << g0 << "\n";
Output:
Col0|Col1 Col2 ----|--------- abc| 1 2 abc| 4 1 abc| 7 5 abc| 10 3 def| 2 20 def| 5 10 def| 8 50 def| 11 30 ghi| 3 200 ghi| 6 100 ghi| 9 500 ghi| 12 300
Sort each sub-table by c2
:
const gtable_t g1 = g0.sort_by<c2>();
cout << g1 << "\n";
Output:
Col0|Col1 Col2 ----|--------- abc| 4 1 abc| 1 2 abc| 10 3 abc| 7 5 def| 5 10 def| 2 20 def| 11 30 def| 8 50 ghi| 6 100 ghi| 3 200 ghi| 12 300 ghi| 9 500
Ungroup g0
:
const table_t t1 = g1.ungroup();
cout << t1 << "\n";
Output:
Col0 Col1 Col2 -------------- abc 4 1 abc 1 2 abc 10 3 abc 7 5 def 5 10 def 2 20 def 11 30 def 8 50 ghi 6 100 ghi 3 200 ghi 12 300 ghi 9 500
Aggregate each sub-table in g0
using max:
const table_t t2 = g0.max();
cout << t2 << "\n";
Output:
Col0 Col1 Col2 -------------- abc 10 5 def 11 50 ghi 12 500