2017-05-01 65 views
1

我有兩個表格,訂單和訂購項目。我在做銷售的日期一份報告,其中需要包括每個日期各OrderItem的,併爲每個日期每個訂單總deliverycost總costprice和sellingprice:在連接的查詢中選擇DISTINCT行的SUM

表:爲了

orderid date   deliverycost 
1   2000-01-01 5 
2   2000-01-01 3 
3   2000-01-02 0 
4   2000-01-02 4 

表:OrderItem的

orderitemdid orderid costprice sellingprice 
1    1   10   12 
2    1   2   4 
3    2   10   12 
4    3   5   6 
5    3   4   10 
6    4   1   2 

我正在尋找一個查詢,這將提供以下輸出:

date   costprice sellingprice deliverycost 
2000-01-01 22   28    8  
2000-01-02 10   18    4 

我曾嘗試以下SQL:

 SELECT 
      SUM(`orderitem`.`costprice`) AS `costprice`, 
      SUM(`orderitem`.`sellingprice`) AS `sellingprice`, 
      SUM(`order`.`delivery`) AS `delivery`, 
      DATE(`order`.`date`) AS `date`, 
     FROM 
      `order` 
     INNER JOIN 
      `orderitem` 
     ON 
      (`order`.`orderid` = `orderitem`.`orderid`) 
     GROUP BY 
      `date` 
     ORDER BY 
      `date` 

的問題是,我最終交貨價格乘以訂單項目數,所以我希望做的order的SUM()。 delivery在連接發生之前。

回答

1

可能與使用不當報價 的不使用單引號的列名,但是當需要使用backtics

SELECT 
     SUM(`orderitem`.`costprice`) as costprice, 
     SUM(`orderitem`.`sellingprice`) as sellingprice, 
     SUM(`order`.`delivery`) as delivery, 
     DATE(`order`.`confirmdate`) as `date`, 
    FROM `order` 
    INNER JOIN `orderitem` ON `order`.`orderid` = `orderitem`.`orderid` 
    GROUP BY `date` 
    ORDER BY `date` 

你的情況也應努力避免backtics,因爲你沒有分開列名和保留字

SELECT 
     SUM(orderitem.costprice) as costprice, 
     SUM(orderitem.sellingprice) as sellingprice, 
     SUM(order.delivery) as delivery, 
     DATE(order.confirmdate) as date, 
    FROM order 
    INNER JOIN orderitem ON order.orderid = orderitem.orderid 
    GROUP BY date 
    ORDER BY date 

和避免笛卡爾乘積你可以加入彙總表

SELECT 
     SUM(t.costprice) as costprice, 
     SUM(t.sellingprice) as sellingprice, 
     SUM(order.delivery) as delivery, 
     DATE(order.confirmdate) as date, 
    FROM order 
    INNER JOIN (
    SELECT 
     orderitem.orderid 
     SUM(orderitem.costprice) as costprice, 
     SUM(orderitem.sellingprice) as sellingprice 
     from orderitem 
     group by orderitem.orderid 
    ) t ON order.orderid = t.orderid 
    GROUP BY date 
    ORDER BY date 
+0

我已經修復了反引號的單引號,但仍然得到了相同的結果......我傾向於將所有內容都反過來並且因爲生成了很多SQL。 –

+1

回答更新..爲避免笛卡爾產品 – scaisEdge

+0

這就是它:)非常感謝。 –