sql - SQL - get min values from a column based on values from two other columns
问题描述
I am trying to collect values of a column that are less than another value of the column that has a specific value in a second column for each instance of a unique value in a third column.
Here's an example.
user_name | time | succeeds |
---|---|---|
bill | 0300 | no |
bill | 0400 | yes |
bill | 0500 | no |
annie | 1200 | yes |
annie | 1400 | yes |
jonny | 0900 | no |
jonny | 1000 | no |
jonny | 1400 | yes |
jonny | 1900 | yes |
So for each user, I want to find the earliest time they succeed (a 'yes') and then collect all the times below these times.
For bill, this would be 0300 For annie there is no time For jonny this would be 1000 and 0900
解决方案
select t1.*,t2.sumTimeUnSucceeds,t2.concatenateTimeUnSucceeds from
(select user_name,min(time1) as minTimeSucceeds from Mytable
where succeeds = "yes" group by user_name) as t1
left join
(select user_name,sum(time1) as sumTimeUnSucceeds,
group_concat(time1) as concatenateTimeUnSucceeds from Mytable
where succeeds = "no" group by user_name) as t2
on t1.user_name = t2.user_name;
推荐阅读
- c++ - 如何设置 gpp 编译器
- r - 如何根据每个项目中的相似字符从 r 列表中选择项目?
- javascript - 多项选择/更正程序(JavaScript)
- wordpress - MAMP 上的多个 Wordpress 网站
- java - Java 套接字阻塞
- java - 如何从 Android 中的 Firestore 获取数组(数字)
- python - 如何通过索引删除一段字符串?
- rest - Asp.Net Web Api 中的异步操作是否以某种方式帮助用户?
- bot-framework-composer - Bot Framework 作曲家 -Luis 构建失败:
- java - Big Sur 上的 MacOS 应用程序,具有 java 子进程和可访问性 API 权限