改进对单行中两个不同表中的记录计数的查询

时间:2015-12-07 20:11:22

标签: sql sql-server-2012

我有两个表,一个包含当前待售的东西(current_listings),另一个包含购买(sold_items)。两个表中的记录都与卖家(seller_id)相关联。

我想要的是一行代表:

seller_id |目前待售的东西数量购买数量

我有一个查询给我这个(下面),但我认为这是一个简单的任务似乎过于复杂。我确信我错过了一种明显的做法,任何人都可以帮助我看到它吗?

SELECT seller_id,
    sum(current_listings) AS current_listings,
    sum(sold_items) AS sold_items
FROM (
    SELECT seller_id,
        count(*) AS current_listings,
        0 AS sold_items
    FROM listings
    WHERE seller_id IN (xxxx)
    GROUP BY seller_id

    UNION

    SELECT seller_id,
        0 AS current_listings,
        count(*) AS sold_items
    FROM sales
    WHERE seller_id IN (xxxx)
    GROUP BY seller_id
    ) x
GROUP BY seller_id

2 个答案:

答案 0 :(得分:0)

 select seller_id
,count(select 1 from from listings l where l.seller_id = x.sellser_id) as current_listings
,count(select 1 from from sales s where s.seller_id = x.sellser_id) as sold_items
from sellers x
group by seller_id

答案 1 :(得分:0)

我没有真正能够在没有任何数据的情况下测试此查询,但您应该可以执行此操作或类似的操作:

SELECT  cl.seller_id,
        SUM(cl.current_listings) AS current_listings,
        SUM(si.sold_items) AS sold_items
FROM    current_listings cl
    INNER JOIN sold_items si ON si.seller_id = cl.seller_id
GROUP BY cl.seller_id

基本上,您将sold_items表加入current_listings上的seller_id表并汇总(我假设的)列current_listings和{{1在sold_items上使用GROUP BY