简体   繁体   English

MySQL选择去年的每个月中有交易的任何部门

[英]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:

+-----------------------------------+
| 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) 我想执行一个查询,该查询将返回任何一个包含过去一年中每个月至少有1笔交易的部门ID(今天是2011-07-28,我从2010-08-01开始到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;

我相信您需要在进行交易时更新一列,或者需要有一个包含id,交易时间和交易列的表,其中id是id,交易时间是他们进行交易时的时间,每次交易时交易列都增加1进行创建,然后创建一个查询,其中交易大于或等于1并且交易时间大于或等于当前时间-1年(以秒为单位)

好的,有一个变量,它是当前日期,格式与您现在使用的表中的格式相同,然后在数据库的日期+1年大于等于当前日期的情况下执行此操作,如果不是,则该日期大于一年了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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