按一列分组并另外一列

时间:2015-05-13 12:27:09

标签: sql postgresql

我这是一个查询

SELECT * FROM user_state_logs WHERE user_state_logs.user_id = 1
AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05'

返回此

user_id   state   duration
1         call    10
1         call    20
1         wait    30
1         call    10
1         wait    20

我想回复此

user_id   state   duration
1         call    40
1         wait    50

我尝试添加GROUP BY user_state_logs.state

但是我收到了这个错误

  

错误:列“user_state_logs.user_id”必须出现在GROUP BY中   子句或用于聚合函数

所以有两个问题:

为什么我会收到此错误?

我怎样才能让查询以第二种格式返回数据?

3 个答案:

答案 0 :(得分:3)

尝试这样做:

SELECT user_state_logs.state, user_state_logs.user_id, sum(user_state_logs.duration)  as duration
FROM user_state_logs 
WHERE user_state_logs.user_id = 1
AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05'
GROUP BY user_state_logs.state, user_state_logs.user_id

答案 1 :(得分:1)

您应该按user_idstate分组:

SELECT user_id, state, sum(duration)
WHERE user_state_logs.user_id = 1
   AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05'
GROUP BY user_id, state

答案 2 :(得分:0)

您收到错误,因为在使用group by语句时定义选择列表。试试这个:

SELECT user_id, state, duration FROM user_state_logs 
WHERE user_state_logs.user_id = 1
AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05'
GROUP BY user_id, state, duration

SELECT user_id, state, max(duration) FROM user_state_logs 
WHERE user_state_logs.user_id = 1
AND created_at BETWEEN '2015-05-03 11:06:05' AND '2015-05-13 11:06:05'
GROUP BY user_id, state