I have two tables
Account table
id | account_no
-----------------------
1 | 111
2 | 222
Account details
id | act_id (fk) | amount | created_dt_ | created_by
------------------------------------------------
1 | 1 | 10 | 2022-10-30 | SYSTEM
2 | 1 | 100 | 2022-11-05 | user1
3 | 1 | 144 | 2022-11-10 | user2
4 | 1 | 156 | 2022-11-16 | user3
5 | 2 | 50 | 2022-11-05 | SYSTEM
6 | 2 | 51 | 2022-11-10 | user2
7 | 3 | 156 | 2022-11-16 | SYSTEM
I need a query to fetch only rows from account details which has at least 2 records for an account id, and merge those rows to a single row showcasing the initial amount and user who created it and the last amount and who created it, something like this
act_id | ini_amt | ini_dt | ini_usr | fnl_amt | fnl_dt | fnl_usr
-------------------------------------------------------------------------------------
1 | 10 | 2022-10-30 | SYSTEM | 156 | 2022-11-16 | user3
2 | 50 | 2022-11-05 | SYSTEM | 51 | 2022-11-10 | user2
we need only the rows with more than one records. How do i fetch that?
3
Answers
In MySQL 8 you could do it like this.
If you need also information fom account, you simle can join it
fiddle
On older MySQL version which doesn’t support windows functions:
https://dbfiddle.uk/q2Oxq0Ay
We can do this without CTEs, using window functions and conditional aggregation:
In the subquery,
row_number
ranks records of the same account by ascending and descending date, whilecount
checks how many records the account has.Then, the outer query filters on accounts that have more than one record, and on the top/bottom record. We can then pivot the dataset with
group by
and conditional expressions to produce the expected result.