如何使用SQL计算行之间的差异?

时间:2019-06-15 12:55:16

标签: sql difference

我有一个任务,用一个新列创建一个表,其中新列与当前行和下一行的年龄之间存在差异。年龄应按降序排列。是否可以使用SQL? 我不知道我应该使用什么sql,而在任务中没有指定。

我知道方括号中应该有一些内容

SELECT name, age, (...) AS difference
FROM Animals
ORDER BY age DESC;

我拥有的“动物”表

id  |  name  | age
 1  | Molly  |  4
 2  | Jackson|  8 
 3  | Wonka  |  38
 4  | Polly  |  7

结果表应如下所示:

  name  | age | difference
 Wonka  | 38  |  30
 Jackson|  8  |  1
 Polly  |  7  |  3
 Molly  |  4  |

3 个答案:

答案 0 :(得分:4)

您需要 config.action_mailer.perform_caching = false config.action_mailer.default_url_options = { :host => "localhost:3000" } config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.smtp_settings = { address: 'smtp.office365.com', port: 587, user_name: ENV['SMTP_EMAIL'], password: ENV['SMTP_PASS'], authentication: :login, enable_starttls_auto: true } 函数:

lead()

请参见demo
结果:

SELECT 
  name, 
  age, 
  age - lead(age) over (order by age desc, name) AS difference
FROM Animals
ORDER BY age DESC

答案 1 :(得分:2)

您将使用 btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { realm.beginTransaction(); Pets pet = new Pets(); pet.setPetName(etPetName.getText().toString()); pet.setPetType(petTypeLst.get(spTypePets.getSelectedItemPosition())); pet.setPetUrlImage(imagePath); Number maxId = realm.where(Pets.class).max("id"); long nextID; if (maxId == null) { nextID = 1; } else { nextID = maxId.longValue() + 1; } pet.setId(nextID); realm.copyToRealmOrUpdate(pet); realm.commitTransaction(); finish(); } }); / lag()lead()

order by

select a.*, (a - lag(age) over (order by age)) as diff from animals a order by age desc; 中的order by不需要与外部查询中的lag()匹配。第一个定义“上一行”。第二个是用于数据表示。

答案 2 :(得分:0)

您可以使用MAX功能(在相应的window of rows上运行)来获得所需的结果。

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       |
+---------+-----+------------+