2015-11-18 133 views
0

我有一個sqlite子查詢,下面的查詢是計算小時和labour_rate。我現在唯一的問題是我可以從我的子查詢中獲取兩列以輸出主查詢。我試圖根據一些網站的教程來佈置查詢,但需要的幫助,有點讓我過了終點線,我不斷收到一個語法錯誤sqlite返回子查詢多列

SELECT c.customerID, c.customer, sum(ifnull(il.line_price, 0))/10000 AS net, 
    FROM customer AS c 
    LEFT JOIN invoice AS i 
    ON c.customerID = i.customerID 
    LEFT JOIN invoice_line AS il 
    ON i.invoiceID = il.invoiceID 
    (SELECT sum((ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0)) * s.cost_rate)/10000 AS labour_rate, 
    sum((ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0)))/10000 AS 
    FROM timesheet_line AS tl 
    LEFT JOIN timesheet AS t 
    ON tl.timesheetID = t.timesheetID 
    LEFT JOIN staff AS s 
    ON t.staffID = s.staffID 
    WHERE (c.customerID = tl.customerID) AND (t.date BETWEEN '2014-03-01' AND '2015-12-01') 
    GROUP BY tl.customerID) AS time1 
    WHERE (i.date BETWEEN '2014-03-01' AND '2015-12-01') AND (time1.customerID = tl.customerID) 
    GROUP BY c.customerID 
    ORDER BY c.customer ASC 

回答

1

中有幾個語法錯誤這裏。第一個(也可能是最重要的)是你必須將子查詢JOIN分配給結果集的其餘部分。所以經過

LEFT JOIN invoice_line AS il 
    ON i.invoiceID = il.invoiceID 

你將需要添加另一個JOIN語句:

LEFT JOIN 
    (SELECT 
     SUM(...) AS labour_rate, 
     SUM(...) AS hours, 
     tl.customerID 
    FROM 
    ...) AS time1 
ON <your join condition> 

你會在你的子查詢中選擇一些排序字段,你可以加入回發票上即tl.customerID 。 另外,在你的子查詢中,你不能引用它之外的字段,所以當你的子查詢中有WHERE (c.customerID = tl.customerID)時,它會失敗,因爲你試圖引用c.<fieldname>。它需要移至JOIN子句的ON部分。一旦你的JOIN正常工作,那麼你可以改變你的最外層SELECT喜歡的東西

SELECT c.customerID, c.customer, sum(ifnull(il.line_price,0))/10000 AS net, time1.labour_rate, time1.hours 

這裏是我會怎麼做一個例子:

SELECT c.customerID, c.customer, sum(ifnull(il.line_price, 0))/10000 AS net, time1.labour_rate, time1.[hours] 
FROM customer AS c 
    LEFT JOIN invoice AS i 
    ON c.customerID = i.customerID 
    LEFT JOIN invoice_line AS il 
    ON i.invoiceID = il.invoiceID 
    LEFT JOIN 
     (SELECT 
      sum((ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0)) * s.cost_rate)/10000 AS labour_rate, 
      sum((ifnull(tl.mon,0) + ifnull(tl.tues,0) + ifnull(tl.wed,0) + ifnull(tl.thurs,0) + ifnull(tl.fri,0) + ifnull(tl.sat,0) + ifnull(tl.sun,0)))/10000 AS [hours], 
      tl.customerID 
     FROM timesheet_line AS tl 
      LEFT JOIN timesheet AS t 
      ON tl.timesheetID = t.timesheetID 
      LEFT JOIN staff AS s 
      ON t.staffID = s.staffID 
     WHERE (t.date BETWEEN '2014-03-01' AND '2015-12-01') 
     GROUP BY tl.customerID) AS time1 
    ON c.customerID = time1.customerID 
WHERE (i.date BETWEEN '2014-03-01' AND '2015-12-01') 
GROUP BY c.customerID 
ORDER BY c.customer ASC 
+0

非常感謝您的回答更重要的是你的解釋。你已經解釋得非常好,實際上已經沉入其中。希望我可以添加另一個子查詢來計算來自其他表集的其他成本,以獲得最終的輸出結果。 – JK36