MySQL查找第一次没有购买的客户的交易(付款)

时间:2015-07-29 19:03:13

标签: mysql payment

我有一个包含交易的简单表格,我希望每月有多少消费者进行的交易总数超过0且他们的第一笔交易不在那个月。第一笔交易是指客户在该月份第一次购买。

我想要获得的结果如下:

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

我有一个SQL小提琴,我发现同样的事情,但对于那个月内有第一笔交易的消费者。实际上,我正在寻找的查询是相同的,但对于其他消费者而言。

这是小提琴:http://sqlfiddle.com/#!9/31538/24

2 个答案:

答案 0 :(得分:2)

我认为这就是你想要的:

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表有什么:

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我们计算按月分组的上述结果。 我希望你想要它。

答案 1 :(得分:0)

以下查询会返回正确的结果。答案是基于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!