mysql:每个子查询结果的返回列

时间:2018-09-27 03:43:22

标签: mysql

我有3个表:customersordersorder-items。该问题要求编写SELECT语句,该语句将返回带有

的表
  • 客户的电子邮件地址
  • 该客户的订单数量
  • 以及每个订单的总费用


前两点很简单:

SELECT email_address,
       (SELECT SUM(order_id) 
        FROM orders 
        WHERE orders.customer_id = cust.customer_id) as "order_count"
FROM customers as cust


我知道我可以像这样为每个订单获取order_total

SELECT order_id, 
    (SELECT SUM((item_price - discount_amount) * quantity)
     FROM order_items 
     WHERE order_items.order_id = ord.order_id) as "order_total"
FROM orders AS ord


但是,如果我尝试将它们结合起来并做类似的事情:

SELECT email_address,
       (SELECT SUM(order_id)
        FROM orders AS ord
        WHERE ord.customer_id = cust.customer_id) as "order_count",
       (SELECT(SELECT SUM((item_price - discount_amount) * quantity)
         FROM order_items 
         WHERE order_items.order_id = ord.order_id)
         FROM orders AS ord
         WHERE ord.customer_id = cust.customer_id) as "order_total"
FROM customers as cust;

我得到:

  

子查询返回1行以上

我了解为什么我会收到该错误。因为是,所以子查询确实返回多行。我想要的是将这些行的每个值放置在另一列中(至少这就是我解释要问的问题)。例如:

email_address    |  order_count  |  order1_total  |  order2_total  |  etc...
============================================================================
john_doe@foo.com |      2        |     $100       |       $200     |   NULL


数据库表如下:

客户(客户ID,电子邮件地址)
订单(order_id,customer_id)
order_items(item_id,order_id,item_price,折扣数量,数量)


在作业中表达的问题:
(我认为这确实措辞很差,但是我知道什么?):)

编写一个SELECT语句,该语句为具有这些列的订单的每个客户返回一行:

  • “客户”表中的电子邮件地址
  • 订单数计数
  • 每个订单的总金额(提示:首先,从价格中减去折扣金额,然后乘以数量。)

仅返回客户具有多个订单的那些行。 按订单项金额之和对结果集进行降序排序。

1 个答案:

答案 0 :(得分:0)

您可以通过使用GROUP BY的聚合来避免此类错误的子查询:

SELECT
    c.email_address,
    COUNT(DISTINCT o.order_id) AS num_orders,
    COALESCE(SUM(oi.quantity * (oi.item_price - oi.discount_amount)), 0) AS total_amount
FROM customers c
LEFT JOIN orders o
    ON c.customer_id = o.customer_id
INNER JOIN order_items oi
    ON o.order_id = oi.order_id
GROUP BY
    c.customer_id,
    c.email_address;