MySQL 查找未首次购买的客户的交易(付款)

MySQL find transactions (payments) of customers that have not purchased for the first time

我有一个简单的 table,里面有交易,我想知道每个月有多少消费者进行的交易总额大于 0,并且他们的第一笔交易不在那个月。首次交易是指客户在该月首次购买。

我试图得到的结果是以下形式:

+--------+---------+-----------------------------------+
|  Year  |  Month  |  NumOfCustomersWithPositiveTotals |
+--------+----------------------------+----------------+
|  2014  |    1    |                 22                |
+--------+----------------------------+----------------+
|  2014  |    2    |                 10                |
+--------+----------------------------+----------------+

我有一个 SQL fiddle 在那里我找到了同样的东西,但对于那些在那个月内有第一次交易的消费者。实际上,我正在寻找的查询是相同的,但对于其他消费者而言。

这是fiddle:http://sqlfiddle.com/#!9/31538/24

我想这就是你想要的:

SELECT count(consumerId) as NumOfCust, mm, yy FROM
(
    SELECT consumerId, month(date) as mm, year(date) as yy, sum(amount) as total, mdate FROM beta.transaction as t
    LEFT JOIN (
            SELECT min(month(date)) as mdate, consumerId as con FROM beta.transaction
            GROUP BY consumerId
            ) as MinDate ON con = t.consumerId
    GROUP BY month(date), consumerId
    HAVING mdate < mm AND total > 0
) as res
GROUP BY res.mm;

我会尝试从内到外解释它

让我们看看名为 minDate 的 JOIN table 有什么:

SELECT min(month(date)) as mdate, consumerId as con FROM beta.transaction
GROUP BY consumerId

-- Here we find the first date of transaction per consumerId

下一个

SELECT consumerId, month(date) as mm, year(date) as yy, sum(amount), mdate FROM beta.transaction as t
    LEFT JOIN (
            SELECT min(month(date)) as mdate, consumerId as con FROM beta.transaction
            GROUP BY consumerId
            ) as MinDate ON con = t.consumerId
    GROUP BY month(date), consumerId
    HAVING mdate < mm AND total > 0

 -- Here we find total amount per consumerId per month and count only the consumers whose first transact (aka minDate) is lower than current month AND total is greater than 0

最后通过外层SELECT我们统计了上面按月分组的结果。 希望是你想要的。

下面的查询returns正确结果。答案基于 Akis 的回答,在 group by 子句中添加 consumerId 并在支票中添加年份和月份。

select
    tyyyy, tmm, count(tcon) as oldkund_real
from
(
    select
        t.yyyy as tyyyy, t.mm as tmm, t.consumerId as tcon, sum(t.amount) as total, fp.yyyy as fpyyyy, fp.mm as fpmm, fp.consumerId as fpcon
    from
        (
            select
                year(date) as yyyy, month(date) as mm, consumerId, amount
            from
                transaction
        ) as t
        left join
        (
            select
                year(min(date)) as yyyy, month(min(date)) as mm, consumerId
            from
                transaction
            group by
                consumerid
        ) as fp
        on
            t.consumerId = fp.consumerId
        group by
            t.yyyy, t.mm, t.consumerId
        having
            STR_TO_DATE(CONCAT('01,', tmm, ',', tyyyy),'%d,%m,%Y') > STR_TO_DATE(CONCAT('01,', fpmm, ',', fpyyyy),'%d,%m,%Y') and total > 0
) as res
group by
    tyyyy, tmm
order by
    tyyyy, tmm;

非常感谢 Akis!