简体   繁体   中英

How can I get the month that is not yet updated in SQL by inserting another row on every update?

I have a table that contains records of different transaction that is needed to be updated monthly. Once the record for a specific month has been successfully updated, it will insert a new record to that table to indicate that it is already updated. Let's take this example.

**date_of_transaction**   **type**   
2015-04-21              1 //A deposit record
2015-04-24              2 //A withdrawal record
2015-04-29              1
2015-04-30              2
2015-04-30              3 //3, means an update record
2015-05-14              1
2015-05-22              1
2015-05-27              2
2015-05-30              2
2015-06-09              1
2015-06-12              2
2015-06-17              2
2015-06-19              2

Let's suppose that the day today is July 23, 2015. I can only get the data one month lower than the current month, so only the data that I can get are june and downwards records.

As you can see, there is an update performed in the month of April because of the '3' in the type attribute, but in the month of May and June, there are no updates occurred, how can I get the month that is not yet updated?

My approach would be to find all the months first, then find the months whose records were updated. Then select only those months from all months whose records werent updated (A set minus operation).

Mysql query would be something like this

select extract(MONTH,data_of_transaction) from your_table_name where month not in (select extract(MONTH,data_of_transaction) from table where type=3);

This will return you months, which has no type=3 rows

SELECT MONTH([trans-date]) FROM [table] GROUP BY MONTH([trans-date]) HAVING MAX([trans-type])<3

Note: this will not work if 3 is not max value in the column

You can try this;

select * 
from tbl
where date_of_transaction < 'July 23, 2015'
and
date_format(date_of_transaction, '%M-%Y') in (
    select 
        date_format(date_of_transaction, '%M-%Y')
    from tbl
    group by date_format(date_of_transaction, '%M-%Y')
    having max(type) != 3
)

date_format(date_of_transaction, '%M-%Y') will take month-year in consideration and filter the data having type = 3 .

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