我有三张桌子:
customers
,
orders
,和
order-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
DB的表如下所示:
客户(客户id、电子邮件地址)
订单(订单号、客户号)
作业中的问题是:
(我觉得这句话很难说,但我知道什么?)
编写一个SELECT语句,为每个有以下列的订单的客户返回一行:
-
客户表中的电子邮件地址
-
订单数量的计数
-
每个订单的总金额(提示:首先,从价格中减去折扣金额。然后,乘以数量。)
仅返回客户有多个订单的行。
按行项目金额之和按降序排列结果集。