MySQL使用临时表(学习)

时间:2018-12-16 15:47:14

标签: mysql

我目前正在学习SQL,以便从我们的Magento数据库制作一个简单的RFM报告,我目前可以通过导出两个查询并将其粘贴到Excel模板中来做到这一点,我想摆脱Excel模板。

我认为创建一个临时表来保存过去6个月的数据将有助于了解购买方式是否正在发生变化(向客户表明我们正在流失)。

     CREATE TEMPORARY TABLE Months_RFM_6
     SELECT
     customer_email,
     count(*) AS Order_Count,
     MAX(created_at) as Last_Order_Date,
     MIN(created_at) as First_Order_Date,
     SUM(base_total_paid) AS Total_Lifetime_Sales,
     (SUM(base_total_paid) / count(*)) AS AOV,
     SUM(base_total_offline_refunded + base_total_online_refunded) AS Refund_Total,
     AVG(total_qty_ordered) AS UPO
     FROM
     mage_sales_order AS o
     WHERE
     o.created_at > DATE_SUB(now(), INTERVAL 6 MONTH)
    GROUP BY
    customer_email
    ORDER BY
    count(*) DESC,

    SELECT
    customer_email,
    count(*) AS Order_Count,
    MAX(created_at) as Last_Order_Date,
    MIN(created_at) as First_Order_Date,
    SUM(base_total_paid) AS Total_Lifetime_Sales,
    SUM(base_total_paid) / count(*)) AS AOV,
    SUM(base_total_offline_refunded + base_total_online_refunded) AS Refund_Total,
    AVG(total_qty_ordered) AS UPO
    FROM
    mage_sales_order AS o
    GROUP BY
    customer_email
    ORDER BY
    count(*) DESC

我确定临时表和SQL查询之间的语法有问题。直到可以使用临时表,我才将其添加到查询中。

1 个答案:

答案 0 :(得分:0)

一旦创建了临时表,内容便基于in select中的选择结果,因此您应该使用临时表中的select *来查看结果,例如:

CREATE TEMPORARY TABLE Months_RFM_6
SELECT customer_email,
count(*) AS Order_Count,
MAX(created_at) as Last_Order_Date,
MIN(created_at) as First_Order_Date,
SUM(base_total_paid) AS Total_Lifetime_Sales,
(SUM(base_total_paid) / count(*)) AS AOV,
SUM(base_total_offline_refunded + base_total_online_refunded) AS Refund_Total,
AVG(total_qty_ordered) AS UPO
FROM mage_sales_order 
WHERE mage_sales_order.created_at > DATE_SUB(now(), INTERVAL 6 MONTH)
GROUP BY customer_email
ORDER BY  Order_Count DESC
;

select * from Months_RFM_6