以定义的时间段(以月计)的总和

时间:2013-11-25 06:48:52

标签: mysql

在这里有个好人...... 我目前有以下代码,基本上按月累计活动帐户总数。 这很简单,但是我想要在每个类别和定义的时间段内做同样的事情而不仅仅是一个月。超过12个月....请任何想法/帮助....我的大脑是扁平的:(

   SELECT
DATE_FORMAT(s.`DateCreated`,'%Y-%M') AS `Date Created`
, DATE_FORMAT(s.`DateEnd`,'%Y-%M') AS `Date End`
,(@csum := @csum + COUNT(DISTINCT(acc.`AccountId`))) AS Active
FROM (SELECT @csum := 0) AS csums, xx_accountdetails acc
INNER JOIN xx_services s USING(accountid)
LEFT JOIN xx_category cat ON(CategoryId)

INNER JOIN xx_products prod USING(productid)
LEFT JOIN xx_subcategory sc ON(prod.Subcategoryid = sc.SubCategoryId)
LEFT JOIN xx_invoiceline il USING(serviceid)
LEFT JOIN xx_invoices i USING(invoiceid)


WHERE DATE_FORMAT(s.DateStart,'%Y-%m') <= DATE_SUB(NOW(), INTERVAL 1 MONTH)
AND
s.`ProductId` NOT IN (4001,4002)

AND cat.`CategoryId` = '1'

AND
(DATE_FORMAT(s.`DateEnd`,'%Y-%m') >= DATE_SUB(NOW(), INTERVAL 1 MONTH)
OR
(s.`DateEnd` IS NULL
AND s.`IsActive` = 1
AND (s.`SuspendReasonId` != 3 OR s.`SuspendReasonId` IS NULL)))

GROUP BY DATE_FORMAT(s.DateCreated,'%Y-%m')

1 个答案:

答案 0 :(得分:0)

对于日期范围,只需更改日期间隔,例如:

date_sub(now(), interval 12 months)

对于每个类别,您需要按语句添加额外的组:

group by cat.CategoryId, ...

也删除它上面的where子句,否则你只会CategoryId = 1

相关问题