我完全被困在这里,我希望我在其他地方没有忽略答案。
我有两个表,asset
和purchase_order
。
资产
asset_key | description | purchase_order_key
PURCHASE_ORDER
purchase_order_key | order_number | number_of_assets
我试图获取采购订单清单,每个订单都符合以下标准:
例如,假设asset
表有4行具有相同的purchase_order_key
(24),17个项目具有不同的purchase_order_key
(66)。如果purchase_order
24列出4 number_of_assets
,purchase_order
66列出19 number_of_assets
,则查询应返回purchase_order
66,而不是purchase_order
24
答案 0 :(得分:1)
您可以使用子查询:
SELECT *
FROM purchase_order
WHERE number_of_assets > (
SELECT COUNT(*)
FROM asset
WHERE asset.purchase_order_key = purchase_order.purchase_order_key
)
答案 1 :(得分:1)
您需要在加入PO表的COUNT
上执行assets
,然后将其与记录的资产数量进行比较。
SELECT PO.purchase_order_key, COUNT(A.purchase_order_key)
FROM purchase_order PO
LEFT JOIN asset A ON PO.purchase_order_key = A.purchase_order_key
GROUP BY PO.purchase_order_key, PO.number_of_assets
HAVING COUNT(*) > PO.number_of_assets
答案 2 :(得分:0)
我认为这就是你要找的东西:
SELECT
PO.*
FROM
purchase_order PO
INNER JOIN
(
SELECT
A.purchase_order_key,
COUNT(A.asset_key) asset_key_count
FROM
asset A
GROUP BY
A.purchase_order_key
) AC on AC.purchase_order_key = PO.purchase_order_key and AC.asset_key_count < PO.number_of_assets