I have the following data delimited by COMMA.
balance_date,name,wallet_type,available_balance
2020-05-07 13:28:59,wokalap,debit,12345
2020-06-02 08:07:18,wokalap,credit,1116
2020-06-02 08:07:18,wokalap,crypto,113
2020-05-06 59:10:05,wokalap,debit,55795
2020-06-07 08:07:18,wokalap,credit,1448
2020-06-05 08:07:18,wokalap,crypto,546
I want to get the SUM for each wallet_type but I also would ONLY want to get the earliest date across all the records and not for each wallet_type.
I am expecting this as a result:
balance_date | name | wallet_type | available_balance |
---|---|---|---|
2020-05-06 59:10:05 | wokalap | debit | 68140 |
2020-05-06 59:10:05 | wokalap | credit | 2564 |
2020-05-06 59:10:05 | wokalap | crypto | 659 |
Please help figure out the correct script to produce such results. I am using mysql workbench for this.
5
Answers
Using a subquery to find the minimum date, we can try the following simple aggregation:
This can be written as follows :
This gives me correct output as :
Here is a demo using SQLFIDDLE
Updates based on user input :
When user inserts more sample data like this :
Expected output :
The query is as below :
Here is a demo using SQLFIDDLE
Below is a Simple Code that executes in MySQL. Please change it according to your database.
No need for windows functions that are only supported in 8.0+ versions, the above query executes in any MySQL version.
You could try to use sub-queries
Or if you are using MySQL version 8.0+, you could try window function
See demo here
We can do this simply without joins, using window functions and aggregation (assuming MySQL 8.0):
In essence that’s an aggregation query by name and wallet type, where the balance is summed. Then, we use window functions to compute the earliest date over all aggregates.
This scans the table only one, hence it is more efficient than options involving joins for example.
Demo on DB Fiddle: