编辑:我用小提琴试了一下,你需要一个 MAX(或 MIN)将它们分组)在左连接的顶部:
SELECT item_master.item_id,
MAX(item_master.price * tax_master_vat.tax_value / 100) as VAT,
MAX(item_master.price * tax_master_lbt.tax_value / 100) as LBT
FROM item_master
LEFT JOIN item_tax ON item_master.item_id = item_tax.item_id
LEFT JOIN tax_master tax_master_vat ON item_tax.tax_id = tax_master_vat.tax_id
AND tax_master_vat.tax_name = 'VAT'
LEFT JOIN tax_master tax_master_lbt ON item_tax.tax_id = tax_master_lbt.tax_id
AND tax_master_lbt.tax_name = 'LBT'
GROUP BY item_master.item_id
如果没有为某个项目链接 tax_value,它应该返回 NULL(乘以 NULL 为 NULL)。如果您想显示与“null”(或什么都没有)不同的内容,可以使用 COALESCE。如果要包括总价:
如果您想添加价格或总额,您可以在 item_master 表中加入:
SELECT item_master.item_id,
tax.VAT,
tax.LBT,
item_master.price + COALESCE(tax.VAT, 0) + COALESCE(tax.LBT, 0) AS Total
FROM item_master
LEFT JOIN ( SELECT item_master.item_id,
MAX(item_master.price * tax_master_vat.tax_value / 100) as VAT,
MAX(item_master.price * tax_master_lbt.tax_value / 100) as LBT
FROM item_master
LEFT JOIN item_tax ON item_master.item_id = item_tax.item_id
LEFT JOIN tax_master tax_master_vat ON item_tax.tax_id = tax_master_vat.tax_id
AND tax_master_vat.tax_name = 'VAT'
LEFT JOIN tax_master tax_master_lbt ON item_tax.tax_id = tax_master_lbt.tax_id
AND tax_master_lbt.tax_name = 'LBT'
GROUP BY item_master.item_id ) tax ON item_master.item_id = tax.item_id
或者,您可以使用 OVER PARTITION BY 子句(让您仅对 item_id 进行分组,但仍包括价格字段):
SELECT item_id,
price,
VAT,
LBT,
price + COALESCE(VAT, 0) + COALESCE(LBT, 0) AS Total
FROM ( SELECT DISTINCT
item_master.item_id,
item_master.price,
MAX(item_master.price * tax_master_vat.tax_value / 100) OVER (PARTITION BY item_master.item_id) as VAT,
MAX(item_master.price * tax_master_lbt.tax_value / 100) OVER (PARTITION BY item_master.item_id) as LBT
FROM item_master
LEFT JOIN item_tax ON item_master.item_id = item_tax.item_id
LEFT JOIN tax_master tax_master_vat ON item_tax.tax_id = tax_master_vat.tax_id
AND tax_master_vat.tax_name = 'VAT'
LEFT JOIN tax_master tax_master_lbt ON item_tax.tax_id = tax_master_lbt.tax_id
AND tax_master_lbt.tax_name = 'LBT'
) price_and_tax
SQL 小提琴示例