我們有一個 springboot 應用程式,并且有一個場景,我們使用本機查詢將資料插入到基于另一個表上的 groupby 查詢的表中。現在,我需要獲取插入前分組的記錄的所有 id 的串列。
詢問:
insert into table2 (column1,column2)
select column1,column2
from table1
group by column1,column2
現在,我需要獲取分組在 table1 中的 id 串列。可能嗎?
uj5u.com熱心網友回復:
只能訪問表 2,您無法獲取 table1 中分組的 id,除非 column1 或 column2 是 id 本身。
uj5u.com熱心網友回復:
這是一個示例,我們在 users 表中有一個標記,以了解 id 是否已被匯總。該函式回傳要匯總的 id 串列,將資訊插入到表摘要中,并將 id 標記為已插入。
這不考慮在一個月內創建的更多用戶已經匯總(它將為同一月創建第二行)。如果找到月份 年份,可以對其進行修改以更新,但它表明了我理解您正在努力實作的目標。
create table users ( id int, created date, summarised int default 0); insert into users (id, created)values (1,'2020-01-01'), (2,'2020-01-15'), (3,'2020-02-15'); create table summary( year int, month int, num_id int);?
3 行受影響
?
CREATE FUNCTION Summarise() RETURNS TABLE (ID int) LANGUAGE plpgsql AS $BODY$ BEGIN RETURN QUERY SELECT users.id from users where summarised = 0; insert into summary select date_part('year',users.created), date_part('month',users.created) ,count(users.id) from users where users.summarised = 0 group by date_part('year',users.created), date_part('month',users.created); UPDATE users set summarised = 1; END; $BODY$
?
select * from users; select * from summary; select Summarise(); select * from users; select * from summary;編號 | 創建 | 總結 -: | :--------- | ---------: 1 | 2020-01-01 | 0 2 | 2020-01-15 | 0 3 | 2020-02-15 | 0 年份 | 月 | 編號 ---: | ----: | -----: | 總結 | | --------: | | 1 | | 2 | | 3 | 編號 | 創建 | 總結 -: | :--------- | ---------: 1 | 2020-01-01 | 1 2 | 2020-01-15 | 1 3 | 2020-02-15 | 1 年份 | 月 | 編號 ---: | ----: | -----: 2020 | 1 | 2 2020 | 2 | 1
db<>在這里擺弄
uj5u.com熱心網友回復:
既然您使用的是本機查詢,那么像下面這樣的 SQL 級別的分組是否可以解決您的問題?(下面是MYSQL代碼)
select column1,column2, group_concat(id_column)
from table1
group by column1,column2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/440099.html
標籤:sql PostgreSQL 弹簧靴 弹簧数据-jpa
上一篇:為mustache模板引擎配置ViewResolver時出錯
下一篇:如果回傳值為真,請勾選復選框
