简体   繁体   中英

MySQL - Return Latest Date and Total Sum from two rows in a column for multiple entries

For every ID_Number, there is a bill_date and then two types of bills that happen. I want to return the latest date (max date) for each ID number and then add together the two types of bill amounts. So, based on the table below, it should return:

|         1 |    201604 | 10.00     |        |

|         2 |    201701 | 28.00     |        |


tbl_charges
+-----------+-----------+-----------+--------+
| ID_Number | Bill_Date | Bill_Type | Amount |
+-----------+-----------+-----------+--------+
|         1 |    201601 | A         |   5.00 |
|         1 |    201601 | B         |   7.00 |
|         1 |    201604 | A         |   4.00 |
|         1 |    201604 | B         |   6.00 |
|         2 |    201701 | A         |  15.00 |
|         2 |    201701 | B         |  13.00 |
+-----------+-----------+-----------+--------+

Then, if possible, I want to be able to do this in a join in another query, using ID_Number as the column for the join. Would that change the query here?

Note: I am initially only wanting to run the query for about 200 distinct ID_Numbers out of about 10 million. I will be adding an 'IN' clause for those IDs. When I do the join for the final product, I will need to know how to get those latest dates out of all the other join possibilities. (ie, how do I get ID_Number 1 to join with 201604 and not 201601?)

I would use NOT EXISTS and GROUP BY

select, t1.id_number, max(t1.bill_date), sum(t1.amount)
from tbl_charges t1
where not exists (
   select 1
   from tbl_charges t2
   where t1.id_number = t2.id_number and
         t1.bill_date < t2.bill_date
)
group by t1.id_number

the NOT EXISTS filter out the irrelevant rows and GROUP BY do the sum.

I would be inclined to filter in the where :

select id_number, sum(c.amount)
from tbl_charges c
where c.date = (select max(c2.date)
                from tbl_charges c2
                where c2.id_number = c.id_number and c2.bill_type = c.bill_type
               )
group by id_number;

Or, another fun way is to use in with tuples:

select id_number, sum(c.amount)
from tbl_charges c
where (c.id_number, c.bill_type, c.date) in
          (select c2.id_number, c2.bill_type, max(c2.date)
           from tbl_charges c2
           group by c2.id_number, c2.bill_type
          )
group by id_number;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM