gpt4 book ai didi

sql - 按一列分组并对另一列求和

转载 作者:行者123 更新时间:2023-11-29 11:59:47 25 4
gpt4 key购买 nike

这是一个查询

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

但是我得到这个错误

ERROR: column "user_state_logs.user_id" must appear in the GROUP BY clause or be used in an aggregate function

所以两个问题:

为什么会出现这个错误?

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

最佳答案

尝试这样做:

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

关于sql - 按一列分组并对另一列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30214747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com