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;

谢谢。

4

2 回答 2

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

也就是说,除掉重复项的计数。我只会为最快和最脏的查询这样做。

推荐的方式是在join之前对money表做summary:

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
于 2012-12-20T16:31:50.680 回答
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
于 2012-12-20T15:44:26.910 回答