根据行值获取 sql 数据

Getting sql data based on row value

我有一个 table 像这样:

date       |    id
------------------------
2022-04-01 |    1
2022-04-02 |    1
2022-04-03 |    1
2022-04-01 |    2
2022-04-03 |    2
2022-04-02 |    3

我正在尝试获取帐户处于活动状态的最后日期,不包括今天。如果 id 在今天的日期不存在,则它不会包含在最终 table 中。所以对于 id 1 的情况,就是 2022-04-02,对于 id 2,就是 2022-04-01

我可以执行 select max(ds) from table where date != "2022-04-03" 来获取最后日期,但是如何获取每个帐户的最后日期,格式如下:

date       |   id
------------------
2022-04-02 |   1
2022-04-01 |   2

即使我尝试对其进行子查询,我也不确定子查询应该是什么。我试过:

with ids as (select id from table where date="2022-04-03")
select max(date), id from table where id in ids.id

但它给了我以下错误:cannot recognize input near 'ids' '.' 'id' in expression specification

如果我没理解错的话,你可以尝试使用子查询IN

select max(date), id 
from table 
where id IN (
 select id 
 from table 
 where date='2022-04-03'
)
GROUP BY id

您可以使用 Sub-query 来获得您想要的结果 -

SELECT MAX(date_), id    -- I have used date column as date_ as date is reserved word.
  FROM (SELECT date_, id
          FROM your_table
         WHERE date_ < DATE '2022-04-03'); -- Since you need the last day excluding today's date.
 GROUP BY id;

您可以使用 window 函数 ROW_NUMBER 来获取您想要的日期

WITH CTE AS (select id,date, ROW_NUMBER() OVER(PARTITION BY id ORDER BY Date DESC) rn from table)
SELECT id,date FROM CTE where rn = 2

Torpas 是对的,要排除今天登录的你并在 with 子句中添加另一个条件

WITH CTE AS (select id,date, ROW_NUMBER() OVER(PARTITION BY id ORDER BY Date DESC) rn from table WHERE id NOT IN ( SELECT id from table WHERE date = current_date()))
SELECT id,date FROM CTE where rn = 2