我是Oracle SQL的新手,我的问题可能看起来很愚蠢但我在解决问题时遇到了一些困难。
现状: 我有以下表格:供应商,债务人,发票
每个供应商都有各种债务人,每个债务人都有各种发票。 我想创建一个评估,向我展示以下场景:
来自供应商的所有债务人的列表。我还希望在列表中看到债务人曾经没有支付他的发票。我在表Invoice中将此信息称为" payed"可能的值为0(已付款)和1(未付款)。我只想在列表中看到债务人ONCE,所以如果只有一张发票是1,它应该显示我" 1"或"未支付"在列表中。现在,当债务人有100张发票时,它会向我显示债务人100倍的信息" 0"或" 1"。
目前:
SELECT company.company_id,
company.companyname_1,
supplier.supplier_id,
supplier.suppliername_1,
debtor.debtor_id_from_supplier,
debtor_ext.debtorname_1,
debtor_ext.street,
debtor_ext.street_number,
debtor_ext.postcode,
debtor_ext.city,
debtor.approved_limit,
debitor.limit_left,
debitor.limit_status,
debitor.limit_type,
debitor.prosecution,
CASE
WHEN invoice.payed = 0 THEN 'Yes'
ELSE 'No'
END as deb_payment
FROM debtor,
debtor_ext,
company,
supplier,
invoice
WHERE ( company.company_id = supplier.company_id ) and
( supplier.supplier_id = debtor.supplier_id ) and
( debtor.debtor_id = debtor_ext.debtor_id ) and
( debtor.supplier_id = invoice.supplier_id ) and
( debtor.debtor_id_from_supplier = invoice.debtor_id_from_supplier )
CODE CORRECTED! 希望你们能帮帮我
答案 0 :(得分:0)
首先,在您的查询中,您正在执行cross join
这不是必需的,也会影响性能。我建议你在这里使用Inner Join
。
此外,由于未提供架构,我正在为以下架构提供解决方案:
<强>供应商:强>
Supplier_Id (PK) | Supplier_Name
<强>债务人:强>
Debtor_Id (PK) | Debtor_Name | Supplier_Id (FK)
<强>发票:强>
Invoice_Id (PK) | Supplier_Id (FK) | Debtor_Id (FK) | Amount | Payed
<强>查询:强>
Select company.company_id,
company.companyname_1,
s.supplier_id,
s.suppliername_1,
d.debtor_id_from_supplier,
d.debtorname_1,
d.street,
d.street_number,
d.postcode,
d.city,
d.approved_limit,
d.limit_left,
d.limit_status,
d.limit_type,
d.prosecution,
tmp.deb_payment
From
(
SELECT d.supplier_id,
d.debtor_id,
(
CASE
WHEN min(i.payed) <> max(i.payed) Then 'Not Payed'
ELSE 'Payed'
END
)as deb_payment
FROM supplier s
inner join debtor d
on s.supplier_id = d.supplier_id
inner join invoice i
on i.supplier_id = d.supplier_id
and i.debtor_id = d.debtor_id
Group by d.supplier_id,d.debtor_id
) tmp
inner join supplier s
on s.supplier_id = tmp.supplier_id
inner join company
on company.company_id = s.company_id
inner join debtor d
on s.supplier_id = d.supplier_id
inner join debtor_ext de
d.debtor_id = de.debtor_id
;
希望它有所帮助!