2012-12-20 58 views
1

我想從3個表得到2和:總和三個表

tbl_header 
id id_quotation description 
1 1    descr_1 
2 2    descr_2 

tbl_body 
id id_quotation id_item item_cost 
1 1    1  400 
2 1    2  300 

tbl_money 
id id_quotation amount 
1 1    200 
2 1    300 
3 2    100 

所以我需要1個查詢來獲取從tbl_head SUM(tbl_body.item_cost) WHERE tbl_body.id_quotation = 1的說明(在這種情況下,400 + 300 = 700),並SUM(tbl_money.amount) WHERE id_quotation=1(以這種情況200 + 300 = 500)。 Id_quotation是所有表中的相同字段。

我做到了與此查詢:

select head.description, 
      sum(body.item_cost) as sum_1, 
      (select sum(money.amount) 
      from  tbl_money money 
      where money.idquotation=head.idquotation 
      GROUP BY money.id_quotation) as sum_2 
FROM  tbl_body as body, 
      tbl_header as head 
WHERE  head.id_quotation=body.id_quotation 
GROUP BY head.description 

現在,我想,以消除內部查詢select sum(money.amount) from ...和東西取代它像SUM(money.amount),但我總是得到創紀錄的3倍,因此總和的三倍大。不起作用的查詢是:

SELECT  head.description, 
       Sum(body.item_cost) AS sum_1, 
       sum(money.amount) as sum_2 
FROM   (tbl_header head 
       INNER JOIN tbl_body body 
       ON head.id_quotation=body.id_quotation) 
    INNER JOIN tbl_money money 
    ON   head.id_quotation=money.id_quotation 
WHERE   head.id_person=1 
    AND   money.id_quotation=body.id_quotation 
GROUP BY  head.description; 

謝謝。

回答

0
select min(header.description), SUM(body3.item_cost), SUM(money.amount) 
from tbl_header header 
    left outer join tbl_body body on header.id_quotation = body.id_quotation 
    left outer join tbl_body body1 on body1.id< body.id 
    left outer join tbl_body body2 on body2.id> body.id 
    left outer join tbl_money money on money.id_quotation = header.id_quotation and body1.id is null 
    left outer join tbl_body body3 on body3.id_quotation=header.id_quotation and body2.id is null 
where header.id_quotation = 1 
group by header.id_quotation 
0

雖然我會將子查詢放在from子句中並修復連接以使用正確的連接語法,但您的方法很好。有一個技巧可以做你想做的事。雖然我不推薦,但我會告訴你:

select head.description, 
      sum(body.item_cost)/count(distinct money.id) as sum_1, 
      sum(money)/count(distinct money.id) as sum_2 
FROM  tbl_body body join 
      tbl_header head 
      on head.id_quotation=body.id_quotation join 
      tbl_money 
      on money.idquotation = head.idquotation 
GROUP BY head.description 

也就是說,劃分重複計數。我只會這樣做最快和最骯髒的查詢。

推薦的方法是在連接前做對貨幣表摘要:

select head.description, 
      sum(body.item_cost) as sum_1, 
      sum(money) as sum_2 
FROM  tbl_body body join 
      tbl_header head 
      on head.id_quotation=body.id_quotation join 
      (select idquotation, SUM(money) as money 
      from tbl_money 
      group by idquotation 
     ) money 
      on money.idquotation = head.idquotation 
GROUP BY head.description