fby

Apply an aggregate or a transformation to groups.

Example

Define columns and table:

#include <cpptables/table.hh>
#include <iostream>

using namespace tables;
using namespace std;

struct col0  { constexpr static char const * const name = "col0"; };
struct col1  { constexpr static char const * const name = "col1"; };
struct col2  { constexpr static char const * const name = "col2"; };

using table_t = table<
  pair<col0,string_view>,
  pair<col1,unsigned>,
  pair<col2,double>
>;

Construct table:

  const table_t t(
    {"A", "B", "C", "A", "B", "C", "A", "B", "C"},
    {1,10,100,2,20,200,3,30,300},
    {100.0,200.0,300.0,400.0,500.0,600.0,700.0,800.0,900.0}
  );
  cout << t << "\n";

Output:

col0 col1 col2
--------------
   A    1  100
   B   10  200
   C  100  300
   A    2  400
   B   20  500
   C  200  600
   A    3  700
   B   30  800
   C  300  900

Sum col1, and avg col2 by col0

  const auto fsum = [](const column<auto>& xs) { return xs.sum(); };
  const auto favg = [](const column<auto>& xs) { return xs.avg(); };
  const table_t t1 = t.fby<col0>().agg<col1,col2>(fsum,favg);
  cout << "sum col1,avg col2 by col0:\n" << t1 << "\n";

Output:

col0 col1 col2
--------------
   A    6  400
   B   60  500
   C  600  600

Reverse col1 by col0:

  const auto freverse = [](const column<auto>& xs) { return xs.reverse(); };
  const table_t t2 = t.fby<col0>().fupdate<col1>(freverse);
  cout << "reverse col1 by col0:\n" << t2 << "\n";

Output:

col0 col1 col2
--------------
   A    3  100
   B   30  200
   C  300  300
   A    2  400
   B   20  500
   C  200  600
   A    1  700
   B   10  800
   C  100  900