分组只有一列Postgresql

时间:2016-01-31 17:27:05

标签: sql postgresql

我有一个postgresql查询,我在其中选择了几列,如下所示:

select * from(
select date_trunc('hour', o.timeofday), count(o.userid),
case when o.userid in(select o.userid from tableOne  where columnA = 'somevalue' group by userid)
Then(
'This equals some value'
)
Else 'some other value'
End as columnB
from tableOne o
inner join tableTwo t
on o.userid = t.userid
where t.columnC = 'someValue'
group by o.userid, t.columnC, date_trunc('hour', o.timeofday)
order by columnD) x
where columnB = 'someValue'

结果是这样的:

date_trunc | count | columnB
timestamp1     1
timestamp1     1
timestamp1     1
timestamp1     1
timestamp2     1
timestamp2     1

我想要这样的事情:

date_trunc | count | columnB
timestamp1    4
timestamp2    2

我知道为什么我在计数栏中得到全部'1'。这是因为我正在按多种方式进行分组,如果我只按'date_trunc('hour',o.timeofday)'分组,我会得到我想要的结果。但是,如果我删除group by子句中的其他所有内容,我会收到错误消息,说我还需要按其他列进行分组。有没有一种方法可以通过date_trunc进行分组,如果是这样,我该如何实现呢?

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您只想要键列的时间,那么只使用group by中的时间表达式。其余的列是不必要的。正如子查询一样:

select date_trunc('hour', o.timeofday), count(o.userid),
       (case when o.userid in (select o.userid from tableOne where columnA = 'somevalue' group by userid)
            Then 'This equals some value'
            Else 'some other value'
        End) as columnB
from tableOne o inner join
     tableTwo t
     on o.userid = t.userid
where t.columnC = 'someValue'
group by date_trunc('hour', o.timeofday)
having columnB = 'someValue'
order by ??;  -- there is no `ColumnD` defined in the query