This is my query in Postgresql:
SELECT
C.id, S.domen, B.name, C.source_id, ST.name
FROM "calls" C
INNER JOIN "site" S ON S.id=C.site_id
INNER JOIN "sources" ON sources.id=C.source_id
INNER JOIN "brand" B ON B.id = S.id_brand
INNER JOIN "source_types" ST ON ST.id = "sources".type_id
WHERE
("calltime" >= '2017-12-01') AND
("calltime" <= '2017-12-03') AND
(S."id_brand"='6')
ORDER BY "calltime" LIMIT 50
And I get this result:
Now I am trying to group by name(last column) this result to get result like this:
Контекстная реклама - 17
SEO-10
....
And for this I use this query:
SELECT
ST.name, count(ST.name)
FROM "calls" C
INNER JOIN "site" S ON S.id=C.site_id
INNER JOIN "sources" ON sources.id=C.source_id
INNER JOIN "brand" B ON B.id = S.id_brand
INNER JOIN "source_types" ST ON ST.id = "sources".type_id
WHERE
("calltime" >= '2017-12-01') AND
("calltime" <= '2017-12-03') AND
(S."id_brand"='6')
GROUP BY ST.name
ORDER BY count(ST.name) DESC LIMIT 50
But I am getting wrong result:
Seems like it take values from source_id
column.
what am I doing wrong?
3
Answers
It’s possible that the 49 is just a coincidence. Try:
All I did was change it to
count(*)
and addAND C.source_id > 50
to the Where clause. Let’s see if this changes the count.Also you could just run this:
This gives you a total count of all the rows (I removed the GROUP BY). If this number equals the total of your grouped row counts, then they really are the counts. We are looking for
127
which is49 + 30 + 21 + 13 + 9 + 4 + 1
I hope this helps.
The
LIMIT 50
in the second query is executed after theGROUP BY
.If you want to aggregate only the first 50 lines, write the
LIMIT 50
into a subselect and perform theGROUP BY
in the outerSELECT
.Try this, If you call group by before limit the result then group by for the entire records. So first filter then do the group by.