sqlite返回子查询多列

时间:2015-11-18 22:00:48

标签: sql sqlite

我有一个带有以下查询的sqlite子查询,它正在计算小时数和labour_rate。我现在唯一的问题是我可以从子查询中获取两列以在主查询中输出。我已经尝试根据一些网络教程布局查询,但需要一些帮助才能让我超越终点线,因为我不断收到语法错误

  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 个答案:

答案 0 :(得分:2)

这里有一些语法错误。第一个(也可能是最重要的)是您必须将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>。需要将其移动到ON子句的JOIN部分。一旦您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