问题
Have a table of suppliers that have 'approval codes' (VNDAPP) and a table of contracts that have 'requirement codes' (COXA). Contracts can have any number of requirements and suppliers can have any number of approvals.
VNDAPP: (vendor approvals table)
VNUM (vendor number)
REQMT (approval code)
COXA: (contract requirements table)
CONTR (contract number)
REQMT (requirement)
Need to find all suppliers that have approvals that, as a minimum, meet the requirements of a certain contract.
Example contract 7736 has requirements number 1 and 10. There are 27 suppliers that have both of these as a minimum. Since the requirements are variable, I cannot hard code them into the query. I'm not certain this qualifies as a relational division problem...
SELECT VNDNO
FROM VNDAPP
LEFT JOIN COXA ON VNDAPP.REQMT = COXA.REQMT
GROUP BY VNDAPP.VNDNO
HAVING Count(COXA.REQMT) = (SELECT count(*)
FROM COXA WHERE COXA.CONTR = '7736'
GROUP BY COXA.CONTR)
What am I doing wrong??
Thanks in advance!
Example data:
Contract Requirement (COXA):
CONTR REQMT
7736 1
7736 10
7737 1
7737 4
7737 6
7738 5
7739 1
Supplier Approval (VNDAPP):
VNDNO REQMT
10019 1
10020 1
10020 2
10020 10
10021 1
10021 4
10021 5
10021 6
Desired result:
CONTR VNDNO
7736 10020
7737 10021
7738 10021
7739 10019
7739 10020
7739 10021
回答1:
Lets assume that you have two binding tables supplier_approval(supplierid, approvalid)
and contracts_requirement(contractid, requirementid)
, where approvalid
and requirementid
corresponds. Then you can use the following query
select sa.supplierid
from supplier_approval sa
where sa.approvalid IN (
select cr.requirementid
from contracts_requirement cr
where cr.contractid = 7736
)
group by sa.supplierid
having count(distinct sa.approvalid) = (
select count(*)
from contracts_requirement cr
where cr.contractid = 7736
)
回答2:
I think you just want:
SELECT VNDNO
FROM VNDAPP JOIN
COXA
ON VNDAPP.REQMT = COXA.REQMT
WHERE COXA.CONTR = '7736'
GROUP BY VNDAPP.VNDNO
HAVING Count(*) = (SELECT count(*)
FROM COXA
WHERE COXA.CONTR = '7736'
);
That is, count the requirements on the vendor that match the requirements for the contract. Then, check if the total count matches the total for the contract.
This assumes you don't have duplicate requirements on either side.
来源:https://stackoverflow.com/questions/53859081/selecting-suppliers-that-have-at-least-the-same-approval-codes-as-the-contract-r