1

我在这里完全被难住了,我希望我没有忽略其他地方的答案。

我有两张桌子,assetpurchase_order

资产

asset_key | description | purchase_order_key

采购订单

purchase_order_key | order_number | number_of_assets

我正在尝试获取采购订单列表,每个订单都满足以下条件:

  • 具有给定 purchase_order_key 的资产表中的总行数小于具有该 purchase_order_key 的 purchase_order 行中的 number_of_assets 值。

例如,假设该asset表有 4 行相同purchase_order_key(24) 行,17 行不同purchase_order_key(66)。如果purchase_order24 列出 4 number_of_assets,而purchase_order66 列出 19 number_of_assets,则查询应返回purchase_order66,而不是purchase_order24。

4

3 回答 3

1

您可以使用子查询:

SELECT *
FROM purchase_order
WHERE number_of_assets > (
    SELECT COUNT(*)
    FROM asset
    WHERE asset.purchase_order_key = purchase_order.purchase_order_key
)
于 2013-11-01T20:08:12.093 回答
1

您需要COUNT对已assets加入的 PO 表执行一次操作,然后将它们与记录的资产数量进行比较。

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
于 2013-11-01T20:09:30.437 回答
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
于 2013-11-01T20:17:01.657 回答