SQL - 从单独表中的列值中选择记录计数

时间:2013-11-01 19:59:53

标签: sql sql-server database tsql

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

我有两个表,assetpurchase_order

资产

asset_key | description | purchase_order_key

PURCHASE_ORDER

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_order 24列出4 number_of_assetspurchase_order 66列出19 number_of_assets,则查询应返回purchase_order 66,而不是purchase_order 24

3 个答案:

答案 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