我有关于sql的这个问题我将在web服务中使用,如果我能做到这一点。我想要做的是创建一个事务的摘要报告。该交易有标题和行。在交易中,我们将输入许多木板。
在输入之后,我想制作一份报告,将添加属于某一类别的所有木板,然后将所有木板乘以该供应商的价格,以便我可以获得总金额。这是一张图片:
下面是我的sql产生了错误的输出:
select
t1.transaction_num,
wo1.wood_classification_desc,
wo2.wood_specie_desc,
sum(t2.board_foot) as total_board_foot,
su1.price,
sum(t2.board_foot*su1.price) as total_amount
from
"transaction_hdr" t1
left join "transaction_lne" t2 on (t1.transaction_id = t2.transaction_id)
left join "supplier" su2 on (t1.supplier_id = su2.supplier_id)
left join "supplier_price" su1 on (t2.price = su1.price)
left join "wood_classification" wo1 on (t2.wood_classification_id = wo1.wood_classification_id)
left join "wood_specie" wo2 on (wo1.wood_specie_id = wo2.wood_specie_id)
group by
t1.transaction_num,wo1.wood_classification_desc,su1.price,su2.supplier_name,wo2.wood_specie_desc
order by transaction_num,wo2.wood_specie_desc
Evrytime我运行那个sql,它产生这样的东西:
我测试的交易只有五个木板。 Mahogany 6" wider - 7ft. up
和1 Mahogany 5" wider - 7ft. up
下的4个木板。
答案 0 :(得分:2)
我猜,在其中一个左连接中你有多个记录,这意味着它会给你错误的总和(分组将影响左连接后的设置)。
只需运行没有分组的sql并检查你得到了什么。
所以它可能不是导致问题的乘法,而是总和。
答案 1 :(得分:1)
您在supplier_price中有多个记录,价格= 13.33吗?这是我的猜测,因为所有其他连接似乎都在主键上..
编辑:
您的问题是您在价格字段上加入supplier_price,这不是有效密钥。鉴于您的输出没有从supplier_price表中获取任何内容,我倾向于将其从查询中删除,如下所示:
select
t1.transaction_num,
wo1.wood_classification_desc,
wo2.wood_specie_desc,
sum(t2.board_foot) as total_board_foot,
t2.price,
sum(t2.board_foot*t2.price) as total_amount
from
"transaction_hdr" t1
left join "transaction_lne" t2 on (t1.transaction_id = t2.transaction_id)
left join "supplier" su2 on (t1.supplier_id = su2.supplier_id)
left join "wood_classification" wo1 on (t2.wood_classification_id = wo1.wood_classification_id)
left join "wood_specie" wo2 on (wo1.wood_specie_id = wo2.wood_specie_id)
group by
t1.transaction_num,wo1.wood_classification_desc,t2.price,su2.supplier_name,wo2.wood_specie_desc
order by transaction_num,wo2.wood_specie_desc
答案 2 :(得分:0)
这可能会解决问题。但是如果你提供了表(和表的主键)之间的关系,它会有所帮助:
select
t1.transaction_num,
wo1.wood_classification_desc,
wo2.wood_specie_desc,
sum(t2.board_foot)
as total_board_foot,
( SELECT DISTINCT su1.price
FROM "supplier_price" su1
WHERE t2.price = su1.price
) AS price,
sum(t2.board_foot) *
( SELECT DISTINCT su1.price
FROM "supplier_price" su1
WHERE t2.price = su1.price
)
as total_amount
from
"transaction_hdr" t1
left join "transaction_lne" t2
on (t1.transaction_id = t2.transaction_id)
left join "supplier" su2
on (t1.supplier_id = su2.supplier_id)
left join "wood_classification" wo1
on (t2.wood_classification_id = wo1.wood_classification_id)
left join "wood_specie" wo2
on (wo1.wood_specie_id = wo2.wood_specie_id)
group by
t1.transaction_num
, wo1.wood_classification_desc
, su2.supplier_name
, wo2.wood_specie_desc
order by transaction_num
, wo2.wood_specie_desc