How to compare the value of two rows with SQL?(如何用SQL比较两行的值?)
问题描述
我正在使用 sqlite 数据库.我的表架构是
I am using sqlite database. My table schema is
CREATE TABLE performance(area TEXT, name TEXT, score INTEGER, dt TEXT)
表格中的内容是这样的:
The content in the table is like this:
uk|josh|4|2013-11-04 20:00
ca|josh|2|2013-11-05 20:00
us|josh|6|2013-11-05 20:00
uk|andy|5|2013-11-04 20:00
us|andy|1|2013-11-05 20:00
uk|sara|9|2013-11-05 20:00
ca|sara|7|2013-11-06 20:00
ca|sara|2|2013-11-06 20:00
我使用下面的sql语句来选择name及其对应的按name和dt分组的score总和.
I used the following sql statement to select name and its corresponding sum of score grouping by name and dt.
select name, sum(score), dt from performance group by name, dt;
我明白了
josh|4|2013-11-04 20:00
josh|8|2013-11-05 20:00
andy|5|2013-11-04 20:00
andy|1|2013-11-05 20:00
sara|9|2013-11-05 20:00
sara|9|2013-11-06 20:00
现在我想扩展我的查询,以便 sql 语句可以搜索其分数总和在不同时间(dt)没有变化的那个.在这种情况下,输出应该是这样的:
Now I want to expand my query so that the sql statement can search that whose sum of score didn't change at different time(dt). In this case the output should be like:
sara|9|2013-11-05 20:00
sara|9|2013-11-06 20:00
这样的sql怎么写?
推荐答案
这可以通过自(反)join来实现:
This can be achieved by a self (anti) join:
SELECT a.*
FROM (SELECT name, dt, SUM(score) as sum_score
FROM performance
GROUP BY name, dt) a
JOIN (SELECT name, dt, SUM(score) as sum_score
FROM performance
GROUP BY name, dt) b
ON a.name = b.name AND a.sum_score = b.sum_score AND a.dt < b.dt
这篇关于如何用SQL比较两行的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用SQL比较两行的值?
基础教程推荐
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- 带更新的 sqlite CTE 2022-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
