总结三个表

时间:2012-12-20 14:43:08

标签: sql sum

我想从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;

感谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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