【问题标题】:I want to find new purchases made in a category using SQL我想使用 SQL 查找在某个类别中进行的新购买
【发布时间】:2018-02-06 06:32:49
【问题描述】:

我的数据如上所示。

我想找到第二次订购与第一次订购不同类别的客户。例如。在上图中,ALFKI 在他的第一个订单(即 10643)中订购了类别 1、7、8,在他的第二个订单(即 10692)中,他订购了类别 2。我想要一份所有此类客户的列表。提前致谢。

【问题讨论】:

  • 您使用的是哪个数据库系统?您真的是指第一订单和第二订单,还是意味着它们有两个不同的订单且订单不重叠?

标签: sql product customer


【解决方案1】:

我认为你想要一些类似的东西:

    select distinct tbl1.CustomerID from <table> tbl1
   where 
   (select count(*) from <table> tbl2 where tbl1.CustomerID = tbl2.CustomerID
   and 
   tbl1.OrderID <> tbl2.OrderID) > 1
   AND
   tbl1.CategoryID not in
    (select CategoryID from <table> tbl3
        where tbl3.OrderID < tbl1.OrderID
        and tbl1.CustomerID = tbl3.CustomerID)

这里的想法(假设我做对了,没有测试——我知道很危险)是你想要的:

  • 每个用户 ID(只有一次,因此是“不同的”)
  • 如果有多个订单(因此选择计数(*)> 1)
  • 类别不在之前的顺序中(从中选择 CategoryID)

它有两个相关的子查询,因此根据您的数据集大小,它的运行速度可能不会非常快——而且我可能误解了您的要求。不过,希望这足以让您入门。

如果您不知道如何使用相关子查询,请尝试查看此处:Wikipedia - Correlated Subquery

【讨论】:

    猜你喜欢
    • 2019-08-21
    • 2023-04-02
    • 1970-01-01
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多