gpt4 book ai didi

sql - 获取两个日期之间的每一行的最大值?

转载 作者:行者123 更新时间:2023-12-04 13:01:59 26 4
gpt4 key购买 nike

在这里学习sql,我遇到了挑战。

我有下表:

tbl <- data.frame(
id_name = c("a", "a", "b", "c", "d", "f", "b", "c", "d", "f"),
value = c(1, -1, 1, 1, 1, 1, -1, -1, -1, -1),
score = c(1, 0, 1, 2, 3, 4, 3, 2, 1, 0),
date = as.Date(c("2001-1-1", "2002-1-1", "2003-1-1", "2005-1-1",
"2005-1-1", "2007-1-1", "2008-1-1", "2010-1-1",
"2011-1-1", "2012-1-1"), "%Y-%m-%d")
)


+---------+-------+-------+-----------+
| id_name | value | score | date |
+---------+-------+-------+-----------+
| a | 1 | 1 | 2001-1-1 |
| a | -1 | 0 | 2002-1-1 |
| b | 1 | 1 | 2003-1-1 |
| c | 1 | 2 | 2005-1-1 |
| d | 1 | 3 | 2005-1-1 |
| f | 1 | 4 | 2007-1-1 |
| b | -1 | 3 | 2008-1-1 |
| c | -1 | 2 | 2010-1-1 |
| d | -1 | 1 | 2011-1-1 |
| f | -1 | 0 | 2012-1-1 |
+---------+-------+-------+-----------+


我的目标是这样的:

对于每个id_name,我想从当前行= id_name(包括端值)的日期之间的tbl中获取最高分的第一个日期(如果打平局)

例如,id_name'a'应该返回'2001-1-1',因为它的分数是1
id_name'b'的分数为4,因此应返回'2007-1-1':

+---------+----------+
| id_name | date |
+---------+----------+
| a | 2001-1-1 |
| b | 2007-1-1 |
+---------+----------+


到目前为止,这就是我所拥有的,

   sqldf("
SELECT
id_name,
date,
score
FROM
tbl As d
WHERE
score = (
SELECT MAX(score)
FROM tbl As b
WHERE
date >= (
SELECT MIN(date)
FROM tbl
WHERE id_name = b.id_name
) AND
date <= (
SELECT MAX(date)
FROM tbl
WHERE id_name = b.id_name
)
)
")


问题在于,无论当前行值如何,它都将返回具有全局最大值的行

谢谢!

最佳答案

我认为WHERE子句中的相关子查询将适合此处:

SELECT id_name, date
FROM tbl as t1
WHERE score = (SELECT max(score) FROM tbl WHERE id_name = t1.id_name)

关于sql - 获取两个日期之间的每一行的最大值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47338944/

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