feld

feld

Struggling with Ecto, distinct, and sum

Trying my hardest to reproduce this query with Ecto, but struggling:

SELECT DISTINCT("id"), sum("hits") AS hits
FROM "stats_daily"
WHERE ("day" = CURRENT_DATE - 1)
GROUP BY "id"
ORDER BY "hits"
DESC LIMIT 1000

I don’t believe I am meant to use an AS for the sum(“hits”) when using Ecto or I have not been able to find a working variant that uses as

If I use distinct, it becomes DISTINCT ON which is not what I want and it also modifies ORDER BY. I’ve tried to use fragments to work around that, but then ORDER BY is failing because “hits” doesn’t match.

the Ecto query before applying DISTINCT and SUM was like this:

    day = "day"

    from(p in "stats_daily", select: [p.id, p.hits], limit: ^count)
    |> where(fragment("? = CURRENT_DATE - 1", literal(^day)))
    |> order_by(desc: :hits)

Any tips would be greatly appreciated

Marked As Solved

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Can you show the actual ecto query you ran as well as the logged SQL? A key part of my comment was “if you are already grouping”. The error seems to indicate that you aren’t. You need to do something like:

    day = "day"

    from(p in "stats_daily", select: [p.id, sum(p.hits)], limit: ^count)
    |> where(fragment("? = CURRENT_DATE - 1", literal(^day)))
    |> group_by([p], p.id)
    |> order_by([p], desc: sum(p.hits))

Also Liked

feld

feld

This worked.

I had it stuck in my head that I needed DISTINCT because I saw this same change applied in another internal system accessing the same database which modified the query to have both DISTINCT and GROUP BY and the query is working over there.

I should not have just blindly trusted that this was the best solution, but I don’t write SQL all day and it seemed right. :upside_down_face:

Thank you kindly for your time.

edit: the use of |> order_by([p], desc: sum(p.hits))sum(p.hits) here is really surprising to me as it looks like you’re trying to sum it here as well. I’ll have to research this more thoroughly.

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

@feld you have to sort by what is in the result of the query eg the select part. You aren’t selecting p.hits you’re selecting sum(p.hits) so that’s what you have to sort on as well. Postgres is smart enough to not do the sum twice.

Where Next?

Popular in Questions Top

LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New

Other popular topics Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement