【问题标题】:Unsold product query without a cross join?没有交叉连接的未售出产品查询?
【发布时间】:2013-11-05 03:43:00
【问题描述】:

我正在处理“未售出产品”的存储过程。

这是我迄今为止所采取的方法的总结。

注意:生产中最多有 7 种产品,销售表大约有 18,000 种,相对于当前数量增长缓慢。

我的问题是:我是否可以考虑另一种方法来避免爆炸交叉连接的潜在陷阱?

declare @products table (
    productName varchar(50)
)

declare @customers table (
    customerName varchar(50)
)

declare @sales table (
    customerName varchar(50),
    productName varchar(50)

)

insert into @products values ('Product1'), ('Product2')

insert into @customers values ('Customer1'), ('Customer2')

insert into @sales values
     ('Customer1', 'Product1')
    ,('Customer1', 'Product2')
    ,('Customer2', 'Product1')

-- want a row for each customer and each product they
-- have not been sold 
select *
from @customers C
cross join @products P
where not exists(select productName 
                 from @sales S
                 where S.customerName = C.customerName and
                       S.productName = P.productName)

【问题讨论】:

  • 有一张未售出产品的表格和一张已售出产品的表格。
  • 这很有趣……没想到
  • 但他对每个客户都需要它,不仅仅是“没有人购买这件商品”,而是“这个人没有购买这三件商品”。

标签: sql tsql sql-server-2008-r2 reporting cross-join


【解决方案1】:

我认为你做得对,但你可以检查 EXCEPT 是否给你更好的性能:

select C.CustID, P.ProdID
from @customers C
cross join @products P
EXCEPT
SELECT CustID, ProdID
from @sales S
group by CustID, ProdID

很明显,如果您可以减少客户名单,这会有所帮助,例如淘汰去年没有购买任何东西的人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-15
    • 2023-03-26
    • 2012-12-31
    • 2016-06-15
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多