Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Yacine Petitprez committed Jul 7, 2018
1 parent 6079e59 commit 426868a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
11 changes: 11 additions & 0 deletions spec/model/model_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,17 @@ module ModelSpec
end
end

it "can count using group_by" do
temporary do
reinit
9.times do |x|
User.create!({first_name: "user#{x}", last_name: "Doe"})
end

User.query.group_by("last_name").count.should eq(1)
end
end

it "can find_or_create" do
temporary do
reinit
Expand Down
10 changes: 6 additions & 4 deletions src/clear/sql/query/aggregate.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,20 @@ module Clear::SQL::Query::Aggregate
def count(type : X.class = Int64) forall X
# save the `select` column clause to ensure non-mutability of the query
columns = @columns.dup
o = if (@offset || @limit)
X.new(Clear::SQL.select("COUNT(*)").from({query_count: self.clear_select.select("1")}).scalar(Int64))
o = if (@offset || @limit || @group_bys)
subquery = self.dup.clear_order_bys.clear_select.select("1")
X.new(Clear::SQL.select("COUNT(*)").from({query_count: subquery}).scalar(Int64))
else
X.new(self.clear_select.select("COUNT(*)").scalar(Int64))
new_query = self.dup.clear_select.select("COUNT(*)")
X.new(new_query.scalar(Int64))
end
@columns = columns

return o
end

# Call an custom aggregation function, like MEDIAN or other
# Note than COUNT, MIN, MAX and AVG are conveniently mapped.
# Note than COUNT, MIN, MAX and AVG are already conveniently mapped.
def agg(field, x : X.class) forall X
self.clear_select.select(field).scalar(X)
end
Expand Down

0 comments on commit 426868a

Please sign in to comment.