Skip to content

A more sql-like group-by #2607

Closed
Closed

Description

@fdncred

Is your feature request related to a problem? Please describe.
I have a hard time remembering how to use group-by in nushell because I always end up with columns of rows or tables which I'm not looking for.

example:
open movies-2.csv | select 'Lead Studio' 'Worldwide Gross' | group-by '"Lead Studio"' | pivot company gross_values

╭────┬───────────────────────┬─────────────────╮
│ #  │ company               │ gross_values    │
├────┼───────────────────────┼─────────────────┤
│  0 │ The Weinstein Company │ [table 2 rows]  │
│  1 │ Independent           │ [table 19 rows] │
│  2 │ Disney                │ [table 8 rows]  │
│  3 │ Fox                   │ [table 6 rows]  │
│  4 │ 20th Century Fox      │ [table 2 rows]  │
│  5 │ Warner Bros.          │ [table 14 rows] │
│  6 │ Summit                │ [table 5 rows]  │
│  7 │ Paramount             │ [table 4 rows]  │
│  8 │ CBS                   │ [table 1 rows]  │
│  9 │ New Line              │ [table 1 rows]  │
│ 10 │ Sony                  │ [table 4 rows]  │
│ 11 │ Universal             │ [table 8 rows]  │
│ 12 │ Lionsgate             │ [table 2 rows]  │
╰────┴───────────────────────┴─────────────────╯

Describe the solution you'd like
What I'd like to see happen is for a new grouping command to be added to nushell that will work a little more like sql. I have found this rust tool which is fantastic. Here's an example:
gb.exe -f movies-2.csv -k 3 -s 7 --skip_header
produces this output which is close to a nushell looking output but not quite.

 k:3                   | count | sum:7
-----------------------+-------+--------------------
 20th Century Fox      | 2     | 156.75
 CBS                   | 1     | 77.09
 Disney                | 8     | 2214.5
 Fox                   | 5     | 661.85
 Independent           | 19    | 1546.9399999999998
 Lionsgate             | 2     | 152.59
 New Line              | 1     | 20.71
 Paramount             | 4     | 321.21999999999997
 Sony                  | 4     | 403.12
 Summit                | 5     | 1242.26
 The Weinstein Company | 2     | 27.880000000000003
 Universal             | 8     | 1792.04
 Warner Bros.          | 14    | 2462.14

What's going on is gb.exe is saying:

  1. Use this file with -f movies-2.csv
  2. Use column 3 as a group by key with -k 3
  3. Use column 7 as the summing aggregate with -s 7
    I'd rather use column names in place of column numbers because that's a more nu way of doing things.

Here's a couple more examples without much explanation.
This one shows adding two grouping keys. I'm always wanting to add more columns when using group-by and it just-work:tm:
gb.exe -f movies-2.csv -k 3,2 -s 7 --skip_header

 k:3                   | k:2       | count | sum:7
-----------------------+-----------+-------+--------------------
 20th Century Fox      | Drama     | 1     | 117.09
 20th Century Fox      | Romance   | 1     | 39.66
 CBS                   | Comedy    | 1     | 77.09
 Disney                | Animation | 4     | 1264.23
 Disney                | Comedy    | 4     | 950.27
 Fox                   | Comedy    | 5     | 661.85
 Independent           | Comedy    | 7     | 399.07
 Independent           | Drama     | 4     | 69.75
 Independent           | Romance   | 7     | 1048.75
 Independent           | romance   | 1     | 29.37
...

This one shows grouping by column 2 alone.
gb.exe -f movies-2.csv -k 2 -s 7 --skip_header

 k:2       | count | sum:7
-----------+-------+--------------------
 Action    | 1     | 93.4
 Animation | 4     | 1264.23
 Comdy     | 1     | 105.96
 Comedy    | 41    | 6081.730000000002
 Drama     | 13    | 1287.15
 Fantasy   | 1     | 285.43
 Romance   | 12    | 1783.1600000000003
 romance   | 1     | 29.37
 Romence   | 1     | 148.66

There are dozens of command line parameters in gb and I'm not requesting all of them be impemented. Maybe we can just get this added with only multiple columns and sum. Then at a later point look at avg or what additional functionality would be interesting.

Describe alternatives you've considered
This does what I want to do but I find it too foreign and having to remember to use reduce when I'm grouping is a bummer because I never remember.
open movies-2.csv | select 'Lead Studio' 'Worldwide Gross' | group-by '"Lead Studio"' | pivot company gross_values | insert total {get gross_values | reduce -f 0 { = $acc + $it.'"Worldwide Gross"' }} | reject gross_values

╭────┬───────────────────────┬───────────╮
│ #  │ company               │ total     │
├────┼───────────────────────┼───────────┤
│  0 │ The Weinstein Company │   27.8800 │
│  1 │ Independent           │ 1546.9400 │
│  2 │ Disney                │ 2214.5000 │
│  3 │ Fox                   │  722.5700 │
│  4 │ 20th Century Fox      │  156.7500 │
│  5 │ Warner Bros.          │ 2462.1399 │
│  6 │ Summit                │ 1242.2600 │
│  7 │ Paramount             │  321.2200 │
│  8 │ CBS                   │   77.0900 │
│  9 │ New Line              │   20.7100 │
│ 10 │ Sony                  │  403.1200 │
│ 11 │ Universal             │ 1792.0400 │
│ 12 │ Lionsgate             │  152.5900 │
╰────┴───────────────────────┴───────────╯

Additional context
Attached is the zipped csv that I used.
movies-2.zip

Activity

  1. added
    category:enhancement
    on Sep 27, 2020
  2. github-actions commented on Jun 24, 2021

    @github-actions

    This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

  3. github-actions commented on Oct 6, 2021

    @github-actions

    This issue is being marked stale because it has been open for 90 days without activity. If you feel that this is in error, please comment below and we will keep it marked as active.

  4. fdncred commented on Oct 6, 2021

    @fdncred
    ContributorAuthor

    yes, i would still like nushell's group-by to work better, specifically more like csv-group-by linked above.

  5. bbkane commented on Oct 6, 2021

    @bbkane

    Could the normal group-by take inspiration from the dataframe group-by?

  6. fdncred commented on Oct 7, 2021

    @fdncred
    ContributorAuthor

    inspiration, yes. code, probably not. dataframe's tables are very different from nushell's tables.

  7. gwenzek commented on Jan 6, 2022

    @gwenzek

    I'm also seconding this. I find the current group-by not really ergonomic to do aggregations (but it's a hard problem).
    The group-by documentation doesn't attempt to do so

    1. the output of group-by should be pivoted: all group-by script I saw always pivot just after the group by. This forces you to retype the column names by hand. The column containing the groups can be given the name "group", and keep the original column names for the keys.

    2. You still need help to compute aggregates. Currently you need to iterate over each row, and compute an aggregate on the table in the row. In @fdncred example it looked liked insert total {get group | reduce -f 0 { = $acc + $it.'Worldwide Gross' }}, the version I came up with is insert total {$it.group.'Worldwide Gross' | math sum}.
      This isn't too bad unless you want to compute several aggregate. Note that in nu we need to explicit we want to add a new column with the aggregate result while this is the default behavior in SQL and gb.
      I think there should be either:
      a. a way to specify reduction inside the group-by command
      this could look like: group-by 'Lead Studio' -sum 'Worldwide Gross' -max BoxOffice,
      but this requires adding many flags to group-by.
      b. smarter aggregation tools: math sum currently fail on a series of table, and doesn't help creating columns. We could have an agg that both insert a new column and compute statistics on a list of tables or list of series: agg sum group 'Worldwide Gross' this would create a new column 'Worldwide Gross' as well as computing the sum. This way you can chain different aggregation. The syntax could be simplified further by assuming like in SQL that there is only one group available, but not sure about that.

  8. fdncred commented on Jan 6, 2022

    @fdncred
    ContributorAuthor

    it would be cool to have a smarter group-by in engine-q.

  9. gwenzek commented on Jan 26, 2022

    @gwenzek
  10. eitsupi commented on Nov 4, 2022

    @eitsupi
    Contributor

    It would be great if prql was supported!

  11. fdncred commented on Nov 4, 2022

    @fdncred
    ContributorAuthor

    I'm down with just about anything that makes group-by better. I try not to use it now unfortunately.

  12. stormasm commented on Nov 30, 2022

    @stormasm
    Contributor

    one way to move forward on PRQL is to coordinate our efforts with the long term plan of how we want to deal with dataframes.

    ideally we would have polars and datafusion and PRQL somehow work together in a nushell (like) data model that
    emphasizes the strength of all (3) systems...

    one avenue we could go down is our plugin system possibly...
    but its not totally clear (at least to me) how to proceed or move forward....
    but its certainly something we are interested in pursuing...

  13. fdncred commented on Nov 30, 2022

    @fdncred
    ContributorAuthor

    updated with a more modern syntax. i also changed the columns names to not have spaces in them because it was a pain.

    open movies3.csv | 
      select LeadStudio WorldwideGross | 
      group-by LeadStudio | 
      transpose company gross | 
      insert total {
        |g| $g.gross | 
        reduce -f 0 {|i acc| $acc + $i.WorldwideGross}} | 
      reject gross |
      sort-by total
    
    ╭────┬───────────────────────┬─────────╮
    │  # │        company        │  total  │
    ├────┼───────────────────────┼─────────┤
    │  1 │ New Line              │   20.71 │
    │  2 │ The Weinstein Company │   27.88 │
    │  3 │ CBS                   │   77.09 │
    │  4 │ Lionsgate             │  152.59 │
    │  5 │ 20th Century Fox      │  156.75 │
    │  6 │ Paramount             │  321.22 │
    │  7 │ Sony                  │  403.12 │
    │  8 │ Fox                   │  722.57 │
    │  9 │ Summit                │ 1242.26 │
    │ 10 │ Independent           │ 1546.94 │
    │ 11 │ Universal             │ 1792.04 │
    │ 12 │ Disney                │ 2214.50 │
    │ 13 │ Warner Bros.          │ 2462.14 │
    ╰────┴───────────────────────┴─────────╯
    

    compared with prql pq is from prql_query

    pq --from movies3.csv "from movies3 | 
      group [LeadStudio] (
        aggregate [ 
          total = sum WorldwideGross
        ]) | 
      sort [total]"
    +-----------------------+--------------------+
    | LeadStudio            | total              |
    +-----------------------+--------------------+
    | New Line              | 20.71              |
    | The Weinstein Company | 27.880000000000003 |
    | CBS                   | 77.09              |
    | Lionsgate             | 152.59             |
    | 20th Century Fox      | 156.75             |
    | Paramount             | 321.21999999999997 |
    | Sony                  | 403.12             |
    | Fox                   | 722.57             |
    | Summit                | 1242.26            |
    | Independent           | 1546.9399999999998 |
    | Universal             | 1792.04            |
    | Disney                | 2214.5             |
    | Warner Bros.          | 2462.14            |
    +-----------------------+--------------------+
  14. added a commit that references this issue on Dec 31, 2024
  15. yerlaser commented on Jul 28, 2025

    @yerlaser

    I came across while searching for existing feature requests that suggest PRQL so that I could subscribe/vote for it.
    Since you closed the other issue, I believe it's here where you are considering this as an option.

    I also wanted to mentioned a (somewhat awkward) workaround.
    There's db query command which accepts SQL as a string.
    One could substitute SQL string with a call to (prqlc <prql_string>)

    But, of course, a dedicated prql built-in that accepts table, dataframe, db connection as a pipeline input and PRQL query as a string would be awesome.

  16. weirdan commented on Jul 28, 2025

    @weirdan
    Contributor

    updated with a more modern syntax.

    Current approach is not too bad:

    use std-rfc/tables aggregate
    
    open movies-2.csv 
    | select 'Lead Studio' 'Worldwide Gross' 
    | group-by --to-table 'Lead Studio' 
    | aggregate 'Worldwide Gross' --ops {total: {math sum}} 
    | sort-by 'Worldwide Gross_total'
  17. fdncred commented on Jul 28, 2025

    @fdncred
    ContributorAuthor

    Agreed that aggregate has helped significantly. It's one of the few std things I auto import via my config.

  18. fdncred commented on Aug 21, 2025

    @fdncred
    ContributorAuthor

    Let's close this since use std-rfc/tables aggregate works great. Need to move that to std.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    category:enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions