Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unexpected result when composing aggregations with case expressions #5175

Open
2 tasks done
brunorpinho opened this issue Mar 6, 2025 · 0 comments
Open
2 tasks done
Labels
bug Invalid compiler output or panic

Comments

@brunorpinho
Copy link

What happened?

Hi,

I am experiencing a bug where prql generates an invalid SQL because there is a case expression inside a sum. Let me demonstrate.

PRQL input

prql target:sql.clickhouse

from `t`.`table`
group {(group_variable)} (aggregate {
  `new_variable` =  (sum (case [(var | as int) < 10 => 1, true => 0])) * 100 / (count null)
})

SQL output

WITH table_0 AS (
  SELECT
    group_variable,
    COALESCE(
      SUM(
        CASE
          WHEN CAST(var AS int) < 10 THEN 1
          ELSE 0
        END
      ),
      0
    ) AS _expr_0,
    var
  FROM
    t.`table`
)
SELECT
  group_variable,
  (_expr_0 * 100 / COUNT(*)) AS new_variable
FROM
  table_0
GROUP BY
  group_variable

-- Generated by PRQL compiler version:0.13.3 (https://prql-lang.org)

Expected SQL output

SELECT
  group_variable,
  (COALESCE(SUM(
        CASE
          WHEN CAST(var AS int) < 10 THEN 1
          ELSE 0
        END
   ), 0) * 100 / COUNT(*)) AS new_variable
FROM
  t.`table`
GROUP BY
  group_variable

MVCE confirmation

  • Minimal example
  • New issue

Anything else?

For some reason the system breaks the expression into a intermediary CTE for the sum when the case expr exists.

@brunorpinho brunorpinho added the bug Invalid compiler output or panic label Mar 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Invalid compiler output or panic
Projects
None yet
Development

No branches or pull requests

1 participant