带分组的SQL子查询

时间:2018-11-05 13:24:03

标签: mysql sql

SELECT customer_email, count(*) AS Order_Count,

MAX(created_at) as Last_Order_Date, 
SUM(base_total_paid) AS Total_Lifetime_Sales, 
SUM(base_total_offline_refunded+base_total_online_refunded) AS Refund_Total, 

FROM mage_sales_order AS o

WHERE o.created_at > “2018-01-01” 

AND

value NOT IN (Select customer_email 
FROM mage_sales_order
WHERE WHERE o.created_at < “2018-10-01”)

试图删除上周已购买的订单,但是卡在了哪里,而且不确定!感谢您的任何帮助!

2 个答案:

答案 0 :(得分:0)

我认为您想删除订购<'2018-01-01'的电子邮件ID,因此它会在查询下方

SELECT customer_email, count(*) AS Order_Count,     
MAX(created_at) as Last_Order_Date, 
SUM(base_total_paid) AS Total_Lifetime_Sales, 
SUM(base_total_offline_refunded+base_total_online_refunded) AS Refund_Total     
FROM mage_sales_order AS o     
WHERE o.created_at > '2018-01-01' AND    
customer_email NOT IN (Select customer_email 
FROM mage_sales_order
WHERE  o.created_at < '2018-10-01'
)
group by customer_email

答案 1 :(得分:0)

您需要一个group by。您的问题的答案是:

SELECT customer_email, count(*) AS Order_Count,
       MAX(created_at) as Last_Order_Date, 
       SUM(base_total_paid) AS Total_Lifetime_Sales, 
       SUM(base_total_offline_refunded+base_total_online_refunded) AS Refund_Total 
FROM mage_sales_order AS o
WHERE o.created_at < CURRENT_DATE - INTERVAL '1 week'
GROUP BY customer_email;

如果您要过滤尚未下订单的客户

SELECT customer_email, count(*) AS Order_Count,
       MAX(created_at) as Last_Order_Date, 
       SUM(base_total_paid) AS Total_Lifetime_Sales, 
       SUM(base_total_offline_refunded+base_total_online_refunded) AS Refund_Total 
FROM mage_sales_order AS o
GROUP BY customer_email
HAVING MAX(o.created_at) < CURRENT_DATE - INTERVAL '1 week'

请注意,日期/时间函数因数据库而异,因此确切的语法可能因所使用的数据库而异。