mySQL select any department that has had transactions in every month in the last year
Sorry for the specific title, I tied to think of a way to generalize it more but I'm not that knowledgeable - guess that's why I'm asking here...
I've got a table with millions of transactions and one of the columns is the ID of the department that performed that particular transaction:
+-----------------------------------+
| ID | DeptID | Amount | Date |
+-----------------------------------+
| 1 | 46开发者_如何学编程 | 4.99 | 2010-01-01 |
+-----------------------------------+
| 2 | 46 | 2.99 | 2010-03-07 |
+-----------------------------------+
| 3 | 57 | 9.99 | 2010-04-04 |
+-----------------------------------+
I want to perform a query that will return any 1 department ID that contains at least 1 transaction for every month in the last year (today is 2011-07-28, I it to start with 2010-08-01 and end with 2011-07-28)
Is there a way to do this without multiple queries?
SELECT DeptID, COUNT(DISTINCT MONTH(`date`)) AS month_count
FROM Transactions
WHERE `date` >= CURDATE() - INTERVAL 1 YEAR
GROUP BY DeptID
HAVING month_count = 12;
I believe you would need a column to be updated when transactions are made, or have a table with id, transaction time and transactions columns, where id is the id, transaction time is whenever they make transactions and transaction column increments by 1 everytime transaction is made, then create a single query where transaction is greater than or equals 1 and transaction time is greater than or equals current time - 1 year (in seconds)
OK, have a variable which is the current date in same format as in the table you have now, then do where database's date + 1 year is greater than equal to current date, if not then its more than a year old
精彩评论