Mysql检查客户是否每月购买

时间:2017-04-05 08:23:54

标签: mysql

这是我桌子的样本。 (实际表包含更多行)

--------------------------------------------------
fInvoice | fDebtorcode | fCompanyname | fdate
123      | A001        | ABC Company  | 2017-02-01
234      | A002        | CDE Company  | 2017-03-02
345      | A003        | FGH Company  | 2017-03-05
456      | A001        | ABC Company  | 2017-04-02
567      | A001        | ABC Company  | 2017-04-04
678      | A002        | CDE Company  | 2017-04-04

我想了解每月有多少公司从我们这里购买。这是我到目前为止所拥有的:

select 
fdebtorcode As Debtorcode, 
fcompanyname As CompanyName, 
(SELECT COUNT(*) FROM  invoicetable WHERE fdate > '2017-03-31' and fdate < '2017-05-01' and fdebtorcode = Debtorcode) As April,
(SELECT COUNT(*) FROM  invoicetable WHERE fdate > '2017-02-28' and fdate < '2017-04-01' and fdebtorcode = Debtorcode) As March,
(SELECT COUNT(*) FROM  invoicetable WHERE fdate > '2017-01-31' and fdate < '2017-03-01' and fdebtorcode = Debtorcode) As February
from tinvoicehistory 
where fdivision = 'Stationary'
group by fdebtorcode 
order by fdebtorcode

现在,我还有2个要求:

  1. 一个名为&#34;每月购买的专栏&#34;这给了我一个&#34;是&#34;对于每月购买的公司,或者没有&#34; no&#34;如果没有。

  2. 仅显示在这3个月内至少购买过一次的公司。 (我目前的结果显示所有这些,包括已经关闭的那些)

  3. 请告诉我是否有更好的方法。所有帮助赞赏。感谢

2 个答案:

答案 0 :(得分:0)

考虑以下解决方案。我包装您的原始查询,略微修改,然后使用每月总计创建您想要的两列。如果公司在三个月内购买,则会在每月购买列中显示yes。如果公司至少在一个月内进行了购买,那么它会在任何购买列中显示yes

我还删除了子查询,并使用条件聚合将它们替换为CASE个表达式。此外,我使用MONTH()函数而不是像您原来那样检查日期范围,这是笨拙的,甚至有点容易出错。它可能容易出错,因为它很容易破坏一个月的终点,而且二月并不总是每年有28个(闰年可能有29个)。

SELECT t.*,
       CASE WHEN t.February > 0 AND t.March > 0 AND t.April > 0
            THEN 'yes' ELSE 'no' END AS purchased_monthly,
       CASE WHEN t.February > 0 OR t.March > 0 OR t.April > 0
            THEN 'yes' ELSE 'no' END AS purchased_once
FROM
(
    SELECT
        fdebtorcode AS Debtorcode, 
        fcompanyname AS CompanyName,   -- non aggregate column; this may be bad
        SUM(CASE WHEN MONTH(fdate) = 2 THEN 1 ELSE 0 END) AS February,
        SUM(CASE WHEN MONTH(fdate) = 3 THEN 1 ELSE 0 END) AS March,
        SUM(CASE WHEN MONTH(fdate) = 4 THEN 1 ELSE 0 END) AS April
    FROM tinvoicehistory 
    WHERE fdivision = 'Stationary'
    GROUP BY fdebtorcode 
) t
ORDER BY t.fdebtorcode

答案 1 :(得分:0)

您可以查看mysql的MONTH()和YEAR()函数。 然后你可以尝试类似的东西:

SELECT fdebtorcode As Debtorcode, fcompanyname As CompanyName,COUNT(*) AS purchases
FROM tinvoicehistory 
WHERE fdivision = 'Stationary'
GROUP BY YEAR(fdate), MONTH(fdate) DESC, fdebtorcode 
ORDER BY fdebtorcode

开头。