PostgreSQL: Finding the total line total for each product that was sold in the largest order?

时间:2016-04-21 22:10:48

标签: sql postgresql

I'm a college student who is currently taking a Database course, using PostgreSQL. There is one question that seem's to give me some trouble.

Here are two tables:

Table1-orders

Fields-id, order_date, customer_id, credit_card_number, cvv, and order_total

Table2-order_lines

Fields-id, order_id, product_id, quantity, sell_price, and line_total

Here is the question:

What was the total line_total for each product that was sold in the largest order? (largest order_total). Enter 0 if the product was not in the largest order. Make sure to enter both decimal places.

So far, this is the syntax I have:

select product_id, 
sum (line_total * (1) * quantity)
from order_lines
group by product_id;

I was able to output the product_id with the total sum of the line_total but I was wondering how the total line_total for each product was sold in the largest order.

Should I find the id of the largest order based on the order_total? Use a sub query to merge the the two tables to get the final answer? Using the sell_price field with the syntax I have above?

1 个答案:

答案 0 :(得分:0)

首先,您需要获得最大的订单。这是通过获取order_total DESC

排序的第一条记录来完成的
SELECT  *
FROM    orders
ORDER BY
        order_total DESC
LIMIT   1

然后您需要获得最大订单的所有产品。只需将其加入order_lines并选择不同的产品ID:

SELECT  DISTINCT
        product_id
FROM    (
        SELECT  *
        FROM    orders
        ORDER BY
                order_total DESC
        LIMIT   1
        ) o
JOIN    order_lines ol
ON      ol.order_id = o.id

最后,我们需要将此结果集与您的查询相结合,如果产品不是最大的顺序,则用零替换总和:

SELECT  product_id,
        CASE WHEN lo.product_id IS NULL THEN sum_line_total ELSE 0 END
FROM    (
        SELECT  product_id, SUM(line_total) sum_line_total
        FROM    order_lines
        GROUP BY
                product_id
        ) ps
LEFT JOIN
        (
        SELECT  DISTINCT
                product_id
        FROM    (
                SELECT  *
                FROM    orders
                ORDER BY
                        order_total DESC
                LIMIT   1
                ) o
        JOIN    order_lines ol
        ON      ol.order_id = o.i
        ) lo
USING   (product_id)

我们可以通过不计算不是最大订单的产品的总和来进一步优化此查询,但这足以让您前进。