【问题标题】:How can I fetch rows upto some condition for multiple group of ids如何为多组 id 获取某些条件下的行
【发布时间】:2020-06-25 05:15:25
【问题描述】:

如何在多个组的某些条件下获取行

请参考下面的 my_table 当前应用的 order by (1) fk_user_id 升序 (2) created_date 降序

我正在使用 postgresql 和 spring boot jpa、jpql。

1) 请找到查询以创建表并插入数据,如下所示

创建和插入语句:

CREATE TABLE public.my_table
(
  id bigint,
  condition boolean,
  fk_user_id bigint,
  created_date date
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.my_table
  OWNER TO postgres;

INSERT INTO public.my_table(
            id, condition, fk_user_id, created_date)
    VALUES 
    (137, FALSE, 23, '2019-08-28'),
    (107, FALSE, 23, '2019-05-13'),
    (83, TRUE, 23, '2019-04-28'),
    (78, FALSE, 23, '2019-04-07'),
    (67, TRUE, 23, '2019-03-18'),
    (32, FALSE, 23, '2019-01-19'),
    (181, FALSE, 57, '2019-11-04'),
    (158, TRUE, 57, '2019-09-27'),
    (146, FALSE, 57, '2019-09-16'),
    (125, FALSE, 57, '2019-07-24'),
    (378, TRUE, 71, '2020-02-16'),
    (228, TRUE, 71, '2019-12-13'),
    (179, FALSE, 71, '2019-10-06'),
    (130, FALSE, 71, '2019-08-19'),
    (114, TRUE, 71, '2019-06-29'),
    (593, FALSE, 92, '2020-03-02'),
    (320, FALSE, 92, '2020-01-30'),
    (187, FALSE, 92, '2019-11-23'),
    (180, TRUE, 92, '2019-10-17'),
    (124, FALSE, 92, '2019-08-05');

我想获取所有 所有最新的 FALSE 条件直到最后一个 TRUE 的行,然后为该用户跳过其他行。

例如,

1) 用户 id = 23 -- id 为 (137, 107) 的前 2 行将在 2019 年 4 月 28 日获取,它具有 TRUE 条件,因此将跳过其他行

2) 用户 id = 57 -- 只有 1 行 id (181)

3) 用户 id = 71 -- 不会获取任何行,因为它具有最新的 TRUE 条件

同样,我的结果行应该如下所示。

我只能通过以下查询找到 1 个用户的行

select * from user_condition where 
fk_user_id = 23 and created_date > (select max(created_date) from user_condition where fk_user_id = 23 and condition like 'TRUE' group by fk_user_id);

但是,我想要所有 fk_user_id 的行

【问题讨论】:

  • 请将数据以文本而非图像的形式发布。如果有可以使用的数据,则可以更轻松地构建答案。
  • @Nick :正如你所说,我已经描述了创建和插入数据的查询。因为我无法在此处粘贴表格,并且文本中的数据看起来不正确
  • @Strawberry :当我浏览您的链接时,我在此处遵循相同的操作并立即发布创建和插入查询。

标签: postgresql jpa jpql


【解决方案1】:
SELECT t1.*
FROM sourcetable t1
WHERE t1.condition = 'FALSE'
  AND NOT EXISTS ( SELECT NULL
                   FROM sourcetable t2
                   WHERE t1.fk_user_id = t2.fk_user_id 
                     AND t1.created_date < t2.created_date /* or <= */
                     AND t2.condition = 'TRUE' )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-13
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    相关资源
    最近更新 更多