这是我的查询
Select email_address, count(order_id) AS order_count, (sum(item_price - discount_amount) * (quantity)) AS order_total,
(avg(item_price - discount_amount) * (quantity)) AS avg_order_total
from customers join orders
using(customer_id)
join order_items
using(order_id)
group by customer_id > 1, email_address
预期输出
我试图制作想要的输出,但我不确定如何只显示其中的3个。尝试了where where语句,但它最糟糕。
在不使用限制的情况下显示输出的另一种方法是什么?
这是修改查询
Select email_address, count(customer_id) AS order_count, sum((item_price - discount_amount) * (quantity)) AS order_total,
round(avg((item_price - discount_amount) * (quantity)),2) AS avg_order_total
from customers join orders
using(customer_id)
join order_items
using(order_id)
group by customer_id
order by count(customer_id) desc limit 3
我试图在不使用限制的情况下产生预期的输出,但我无法弄清楚如何。上面是我的查询,我使用limit来显示结果,它显示了我想要的输出。我尝试使用where语句,但是当我这样做时它并没有运行我的查询。
答案 0 :(得分:0)
你可以尝试这个查询吗?
SELECT c.email_address,
count(o.order_id) AS order_count,
(sum(i.item_price - i.discount_amount) * (i.quantity)) AS order_total,
(avg(sum(i.item_price - i.discount_amount) * (i.quantity))) AS avg_order_total
from customers c
INNER JOIN orders o ON c.customer_id = o.customer_id
INNER JOIN order_items i ON o.order_id = i.order_id
GROUP BY email_address;
有几点需要注意:
答案 1 :(得分:0)
这个建议有几个猜测:
SELECT
c.email_address
, COUNT(DISTINCT o.order_id) AS order_count
, (SUM(oi.item_price - oi.discount_amount) * (oi.quantity)) AS order_total
, (AVG(oi.item_price - oi.discount_amount) * (oi.quantity)) AS avg_order_total
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE c.customer_id > 1
GROUP BY
c.email_address
在连接多个表时,最好指定列来自哪个表。为了简化这一点,可以给每个表提供别名,并且通常的方法是使用第一个字母,例如对于这组表:c,o,oi
在某些地方放置别名时我可能猜错了,而我无法解决这个问题,因为我不知道你的桌子。
+ EDIT
顺便说一句,我还将DISTINCT
包含在订单计数中,如果您不这样做,则会计算订单商品的数量。
SELECT
c.email_address
, COUNT(DISTINCT o.order_id) AS order_count
, (SUM(oi.item_price - oi.discount_amount) * (oi.quantity)) AS order_total
, (SUM(oi.item_price - oi.discount_amount) * (oi.quantity))
/ COUNT(DISTINCT o.order_id) AS avg_order_total
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
WHERE c.customer_id > 1
GROUP BY
c.email_address