Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

counting smth in betweeen 1 month of register in mysql

I want to count some data in a month after a specific date.
the table looks like this

date user_id tx_id
2022-07-08 123 1
2022-07-08 124 2
2022-07-10 123 3

I want to count every tx_id that user_id number 123 made in the a month from it’s first tx_id. like how many tx_id s does user 123 made from 2022-07-08 to 2022-08-08?

I couldn’t find any thing that can handle both finding if it’s first tx_id and counting the other tx_ids one month from that date.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

use this query :

SELECT COUNT(*) AS transaction_count
FROM your_table
WHERE user_id = 123
AND tx_id IN (
    SELECT tx_id
    FROM your_table
    WHERE user_id = 123
    ORDER BY date ASC
    LIMIT 1
)
AND date >= (
    SELECT MIN(date)
    FROM your_table
    WHERE user_id = 123
)
AND date <= (
    SELECT DATE_ADD(MIN(date), INTERVAL 1 MONTH)
    FROM your_table
    WHERE user_id = 123
);

here is the optimized query without subquery:

SELECT COUNT(*) AS transaction_count
FROM your_table
WHERE user_id = 123
AND date >= (
    SELECT MIN(date)
    FROM your_table
    WHERE user_id = 123
)
AND date <= DATE_ADD(
    (
        SELECT MIN(date)
        FROM your_table
        WHERE user_id = 123
    ),
    INTERVAL 1 MONTH
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading