如何在sql中的子查询中创建2列的总和?

时间:2017-08-07 03:26:01

标签: mysql

我想制作一个显示number_ordered和price相乘的coulmn但是当我使用这个查询时

SELECT  customer_num AS 'Customer Number' , 
        order_num AS 'Order Number' ,
        order_date AS 'Order Date' , 
        (SELECT SUM(quoted_price * num_ordered ) FROM tbl_order_line ) AS 'ORDER_TOTAL'
FROM tbl_orders ;

它给了我每个领域的相同记录 这是tbl_order_line

    CREATE TABLE tbl_order_line
(
    order_num       CHAR(5) NOT NULL,
    part_num          CHAR(4) NOT NULL,
    num_ordered     DECIMAL(3,0) UNSIGNED NOT NULL,
    quoted_price    DECIMAL(6,2) UNSIGNED NOT NULL,
    PRIMARY KEY(order_num, part_num),
    FOREIGN KEY(order_num) REFERENCES tbl_orders(order_num),
    FOREIGN KEY(part_num)  REFERENCES tbl_part(part_num)
);

这是tbl_orders

    CREATE TABLE tbl_orders
(
    order_num           CHAR(5) PRIMARY KEY,
    order_date          DATE NOT NULL,
    customer_num        CHAR(3) NOT NULL,
    FOREIGN KEY(customer_num) REFERENCES tbl_customer(customer_num) 
);

expected result result i get

1 个答案:

答案 0 :(得分:-1)

http://www.sqlfiddle.com/#!9/77874/42

SELECT 
tmp2.sums,
tmp2.order_num orders,
tbl_orders.customer_num ,
tbl_orders.order_num ,
tbl_orders.order_date 
FROM tbl_orders 
,
(SELECT  order_num,SUM(quoted_price * num_ordered ) sums FROM tbl_order_line 
 group by order_num
) as tmp2
 group by orders