在明确执行

时间:2015-10-08 12:46:50

标签: sql postgresql

我有一个查询,例如

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'

问题是count over()在执行distinct之前计算结果,因此会返回不正确的值。

我可以移除distinct并使用group by,但这会为每个组提供count,我想要这些值的总和。

我可以做一个子查询,但问题是这个查询是在应用程序中构建的,所以我必须做一些字符串操作,将where子句添加到子查询和主sql体。

有没有办法让count在执行distinct之后显示结果?

由于

2 个答案:

答案 0 :(得分:5)

这应解决问题

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

答案 1 :(得分:1)

使用group by,但使用正确的表达式:

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 . . .