如何使用SQL计算行之间的差异?
我的任务是创建一个包含一个新列的表,该列在当前行和下一行的年龄之间存在差异。年龄应该按降序排列。可以使用SQL吗? 我不知道应该使用什么样的sql,任务中也没有指定 我知道括号里应该有东西如何使用SQL计算行之间的差异?,sql,difference,Sql,Difference,我的任务是创建一个包含一个新列的表,该列在当前行和下一行的年龄之间存在差异。年龄应该按降序排列。可以使用SQL吗? 我不知道应该使用什么样的sql,任务中也没有指定 我知道括号里应该有东西 SELECT name, age, (...) AS difference FROM Animals ORDER BY age DESC; 我有一张“动物”的桌子 身份证|姓名|年龄 1 |莫莉| 4 2 |杰克逊| 8 3 |旺卡| 38 4 |波利| 7 结果表应如下所示: name | age
SELECT name, age, (...) AS difference
FROM Animals
ORDER BY age DESC;
我有一张“动物”的桌子
身份证|姓名|年龄
1 |莫莉| 4
2 |杰克逊| 8
3 |旺卡| 38
4 |波利| 7
结果表应如下所示:
name | age | difference
Wonka | 38 | 30
Jackson| 8 | 1
Polly | 7 | 3
Molly | 4 |
姓名|年龄|差异
旺卡| 38 | 30
杰克逊| 8 | 1
波利| 7 | 3
莫莉| 4|
您可以使用lag()
select a.*,
(a - lag(age) over (order by age)) as diff
from animals a
order by age desc;
lag()
中的order by
不需要与外部查询中的order by
匹配。第一个定义“前一行”。第二个是用于显示数据。您需要lead()
函数:
SELECT
name,
age,
age - lead(age) over (order by age desc, name) AS difference
FROM Animals
ORDER BY age DESC
请参阅。
结果:
您可以使用MAX功能实现所需的结果,该功能在相应的计算机上运行
输出:
+---------+-----+------------+
| name | age | difference |
+---------+-----+------------+
| Wonka | 38 | 30 |
| Jackson | 8 | 1 |
| Polly | 7 | 3 |
| Molly | 4 | NULL |
+---------+-----+------------+
ANSI/ISO标准SQL,其中SQL标签在本网站上有LAG()
和LEAD()
,以便能够读取上一条记录和下一条记录。但是,由于您提到了括号,我假设您使用的是SQL Server(MSSQL)作为RDM,一个问题的可能重复,当出现“关系”时会发生什么在年龄中。@Lisaage-lead(age)over(order by age desc,name)AS difference
甚至可能是更好地处理“ties”的“必需条件”。ASlead(age)over(order by age desc)
在年龄匹配时将随机返回。。但不确定这对公司有多重要topicstarter@Lisaage-lead(age)over(order by age desc,name)AS difference
甚至可能是“必需”的,以便更好地处理“ties”。ASlead(age)over(order by age desc)
将在年龄绑定时随机返回。。但不确定这对topicstarter有多重要
> name | age | difference
> :------ | --: | ---------:
> Wonka | 38 | 30
> Jackson | 8 | 1
> Polly | 7 | 3
> Molly | 4 |
with Animals as (
select 1 as id, 'Molly' as name, 4 as age union all
select 2, 'Jackson', 8 union all
select 3, 'Wonka', 38 union all
select 4, 'Polly', 7
)
select
name, age,
age - max(age) over(
order by age
rows between unbounded preceding
and 1 preceding
)
from Animals
order by age desc;
+---------+-----+------------+
| name | age | difference |
+---------+-----+------------+
| Wonka | 38 | 30 |
| Jackson | 8 | 1 |
| Polly | 7 | 3 |
| Molly | 4 | NULL |
+---------+-----+------------+