Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting count over() value after distinct executed

Tags:

sql

postgresql

I have a query such as

select
distinct
t.*,
t.name + ' ' + t.lastname as customername
count(t.id) over() as count
from 
table t
inner join othertable o
on t.id = o.tableid
where t.blah = 'aaa'

The problem is that the count over() calculates the results before the distinct is executed and therefore returns an incorrect value.

I could remove the distinct and use group by but this will give the count for each group and I want the sum of those values.

I could do a subquery but the problem is this query is getting built up inside an application so I'd have to do some string manipulation to add the where clause to the subquery and main sql body.

Is there a way to get the count show the results after the distinct is executed?

Thanks

like image 603
Jon Avatar asked Jan 23 '26 12:01

Jon


2 Answers

This should solve the problem

select count(v.col_a) over() as count,
       v.*
from (select distinct t.col_a, t.col_b, ... --all columns you need
             t.name + ' ' + t.lastname as customername
      from table t
           inner join othertable o on t.id = o.tableid
      where t.blah = 'aaa') v
like image 70
Kirill Kin Avatar answered Jan 25 '26 08:01

Kirill Kin


Use group by, but use the correct expression:

select t.*,
       t.name + ' ' + t.lastname as customername
       sum(count(t.id)) over() as total_count
from table t inner join
     othertable o
     on t.id = o.tableid
where t.blah = 'aaa'
group by . . .
like image 24
Gordon Linoff Avatar answered Jan 25 '26 08:01

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!