Class: ActiveRecord::Refined::AST::Aggregate

Inherits:
Node
  • Object
show all
Includes:
Arithmetics, Predications, Windowing
Defined in:
lib/active_record/refined/ast.rb

Overview

An aggregate -- COUNT, SUM, AVG, MIN, MAX -- over a group, or, given Windowing#over, a window.

Instance Method Summary collapse

Methods included from Windowing

#over

Methods included from Arithmetics

#&, #*, #+, #-, #/, #<<, #>>, #^, #bitwise_and, #bitwise_not, #bitwise_or, #bitwise_xor, #|, #~

Methods included from Predications

#!=, #!~, #<, #<=, #==, #=~, #>, #>=, #between?, #bury, #casecmp?, #contains?, #dig, #dig_text, #distinct_from?, #end_with?, #except, #false?, #ilike?, #in?, #include?, #intersect?, #key?, #keys, #like?, #member?, #not_between?, #not_distinct_from?, #not_false?, #not_ilike?, #not_in?, #not_like?, #not_null?, #not_true?, #null?, #start_with?, #subset?, #superset?, #true?, #when

Methods inherited from Node

#as, #asc, #collate, #desc

Constructor Details

#initialize(operand, function, distinct: false, condition: nil) ⇒ Aggregate

Returns a new instance of Aggregate.



1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
# File 'lib/active_record/refined/ast.rb', line 1808

def initialize(operand, function, distinct: false, condition: nil)
  if distinct && !DISTINCT_FUNCTIONS.include?(function)
    raise ArgumentError, "#{function} does not take distinct; it would give the same"
  end
  if distinct && operand == :*
    raise ArgumentError, "count(:*) does not take distinct; name a column"
  end
  @operand = operand
  @function = function
  @distinct = distinct
  @condition = condition
end

Instance Method Details

#filter(condition = nil, &block) ⇒ AST::Aggregate

FILTER (WHERE condition): the aggregate taken over the rows the condition holds for, as a value or a block. Where there is no FILTER clause -- MySQL, SQL Server -- the CASE that means the same.

Examples:

Author.select { [count(:*).as(:all), count(:*).filter { :age < 50 }.as(:young)] }

Returns:



1827
1828
1829
1830
# File 'lib/active_record/refined/ast.rb', line 1827

def filter(condition = nil, &block)
  Aggregate.new(operand, function, distinct: distinct,
                condition: Case.argument(:filter, condition, block))
end