Support aggregate functions in HAVING clause

XMLWordPrintableJSON

    • Type: New Feature
    • Resolution: Duplicate
    • Priority: Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Query
    • None
    • None
    • None
    • None
    • None
    • None
    • None
    • None

      Aggregate functions in HAVING are valid SQL even when absent from SELECT:

      SELECT p.country
      FROM Payment p
      GROUP BY p.country
      HAVING COUNT(*) > 1
      

      Here COUNT is computed per group for filtering only and must not appear in the result. This requires adding a hidden accumulator to $group and it must not be accessible in $project and $sort.

      MongoDB mapping

      [
        {"$group": {"_id": {"country": "$country"}, "_having_0": {"$sum": 1}}},
        {"$match": {"_having_0": {"$gt": 1}}},
        {"$project": {"_id#country": "$_id.country", "_having_0": 0}}
      ]
      

      Potential implementation approach

      HAVING with aggregates requires a two-phase approach to avoid a chicken-and-egg problem ($group must be emitted before $match, but HAVING must be scanned to know what accumulators to add).

      Acceptance criteria

      • Aggregate functions in HAVING that do not appear in SELECT are computed as hidden accumulators.
      • Aggregate functions shared between HAVING and SELECT reuse the same accumulator - no duplication in $group.
      • Expressions wrapping aggregates (e.g. AVG + 1) are supported -  the accumulator is registered for the inner aggregate and the outer arithmetic is resolved in $project.
      • Integration tests cover all combinations: HAVING aggregate only, HAVING + SELECT (same and different functions), HAVING with expression wrapping aggregate, HAVING + ORDER BY, SELECT with expression wrapping aggregate

            Assignee:
            Unassigned
            Reporter:
            Slav Babanin
            None
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: