简体   繁体   English

计算日期时间字段中的年和月条目

[英]Counting year and month entries from datetime fields

I have a problem constructing a mysql query: 我在构造mysql查询时遇到问题:

I have this table "tSubscribers" were I store the subscribers for my newsletter mailing list. 我在“ tSubscribers”表中存储了我的通讯邮件列表的订阅者。

The table looks like this (simplified): 该表如下所示(简化):

--
-- Table structure for tSubscriber
--
CREATE TABLE tSubscriber (
    fId INT UNSIGNED NOT NULL AUTO_INCREMENT,
    fSubscriberGroupId INT UNSIGNED NOT NULL,
    fEmail VARCHAR(255) NOT NULL DEFAULT '',
    fDateConfirmed DATETIME NOT NULL DEFAULT '0000-00-00 00:00:00',
    fDateUnsubscribed TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
    PRIMARY KEY (fId),
    INDEX (fSubscriberGroupId),
) ENGINE=MyISAM;

Now what I want to accomplish is to have a diagram showing the subscriptions and unsubscriptions per month per subscriber group. 现在,我要完成的工作是创建一个图表,显示每个订户组每月的订阅和取消订阅。

So I need to extract the year and months from the fDateConfirmed, fDateUnsubscribed dates, count them and show the count sorted by month and year for a subscriber group. 因此,我需要从fDateConfirmed,fDateUnsubscribed日期中提取年和月,对它们进行计数,并显示订户组按月和年排序的计数。

I think this sql query gets quite complex and I just can't get my head around it. 我认为此sql查询变得相当复杂,我只是无法解决。 Is this even possible with one query. 一个查询甚至可能做到这一点。

You will need two separate queries, one for subscriptions and other for unsubscriptions. 您将需要两个单独的查询,一个用于订阅,另一个用于取消订阅。

SELECT COUNT(*), YEAR(fDateConfirmed), MONTH(fDateConfirmed) FROM tSubscriber GROUP BY YEAR(fDateConfirmed), MONTH(fDateConfirmed)
SELECT COUNT(*), YEAR(fDateUnsubscribed), MONTH(fDateUnsubscribe ) FROM tSubscriber GROUP BY YEAR(fDateUnsubscribed), MONTH(fDateUnsubscribed)

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

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