GROUP BY子句的postgres查询错误

时间:2014-04-14 10:00:22

标签: postgresql

我有一个表login_logout时间,就像

id  user_id     start               end                      total(sec)
--------------------------------------------------------------------------------------
1   1   "2014-04-14 12:17:54.772"   "2014-04-14 12:17:55.772"   1
2   1   "2014-04-14 12:22:41.763"   "2014-04-14 12:31:14.295"   512
3   2   "2014-04-14 12:43:51.823"   "2014-04-14 12:48:40.706"   288
4   2   "2014-04-14 13:22:51.656"   "2014-04-14 13:22:52.656"   1

我想要这种格式的数据

    user : 1
------------------------------------------------------------------
        start_time      end_time    total (seconds)
        "12:17"         "12:17"         1
        "12:22"         "12:31"         512
                                    total:  513 
    user : 2
------------------------------------------------------------------
        "12:43"         "12:48"         288
        "13:22"         "13:22"         1
                                    total   289

但是我以这种格式获得约会

user : 1
------------------------------------------------
start_time  end_time    total (seconds)
"12:17"     "12:17"     1
                total : 1
user : 1
------------------------------------------------
"12:22"     "12:31"     512
                total : 512

user : 2 
------------------------------------------------
"12:43"     "12:48"     288
                total : 288

user : 2 
------------------------------------------------
"13:22"      "13:22"    1
                total : 1

查询是:

SELECT l.user_id, 
      SUBSTR(cast (l.start::time as text), 1,5) startTime,
      SUBSTR(cast (l::time as text), 1,5) endTime,
       sum(total)
FROM   login_logout l 
GROUP  BY l.user_id, 
          starttime, 
          endtime

我知道这是因为startTime,endTime在group by子句中添加。

当我删除它时,我会出名并且must appear in the GROUP BY clause or be used in an aggregate function'错误。

你能帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

尝试这样

select  l.user_id,  
SUBSTR(cast (min(l.stime)::time as text), 1,5) startTime,
SUBSTR(cast (max(l.etime)::time as text), 1,5) endTime,
sum(total) from login_logout l group by l.user_id

它给出以下输出:

   uid  startTime endTime  total

    1   12:17    12:31    513
    2   12:43     13:22    289

select cast(uid as text) || '2' as ord, null as uid,'' as 
starttime,'' as endtime, sum(tse) from tt group by uid

union all

SELECT cast(uid as text) || '1' as ord, l.uid, 
      SUBSTR(cast (min(l.stime)::time as text), 1,5) startTime,
      SUBSTR(cast (max(l.etime)::time as text), 1,5) endTime,
       sum(tse)
FROM   tt l 
GROUP  BY l.uid, 
          l.stime, 
          l.etime order by ord

ord列仅用于按

排序

此输出显示如下

ord uid  startTime endTime  total
11   1     12:22     12:31   512
11   1     12:17     12:17     1
12                           513
21   2     13:22     13:22     1
21   2     12:43     12:48   288
22                           289