在特定商品的订单日期之前订购的商品

时间:2017-04-05 08:59:10

标签: mysql sqlite

这是我的表

|Customer|Order Nr.| Items | date of order |
|    1   |    1    | Item1 | date 1        | 
|    1   |    1    | Item2 | date 1        |
|    1   |    2    | Item1 | date 2        |
|    1   |    2    | Item3 | date 2        |
|    1   |    3    | Item6 | date 9        | --> Item 6,   date 9 is reference date
|    1   |    6    | Item5 | date 14       |
|    1   |    7    | Item6 | date 18       | --> Item 6 again, date 18 is not relevant
|    2   |    1    | Item3 | date 4        |
|    2   |    1    | Item5 | date 4        |
|    2   |    2    | Item9 | date 3        |
|    2   |    2    | Item6 | date 3        | --> date 3 is reference date
|    2   |    3    | Item6 | date 4        | --> Item 6 again, date 4 is not relevant

我需要在参考日期之前获得客户的所有订单和物品。 参考日期是此客户第一次订购Item6的日期。此表中的客户列表是订购Item6的客户。

表格必须如下:

|Customer| Items |
|    1   | Item1 |
|    1   | Item2 |
|    1   | Item3 |
|    2   | Item3 |
|    2   | Item5 |
|    2   | Item9 |

resutlting表不应该包含Item6信息!

非常感谢任何建议!

2 个答案:

答案 0 :(得分:1)

对于客户 X ,此查询会查找参考日期:

SELECT min(DateOfOrder)
FROM MyTable
WHERE Customer = X
  AND Items = 'Item6';

现在,您可以在相关子查询中使用它来过滤行:

SELECT Customer,
       Items
FROM MyTable AS T1
WHERE DateOfOrder < (SELECT min(T2.DateOfOrder)
                     FROM MyTable AS T2
                     WHERE T2.Customer = T1.Customer
                       AND T2.Items = 'Item6');

答案 1 :(得分:1)

这将返回每位客户购买Item6的最短日期

select  Customer, min(DateOfOrder)
from    yourTable
where   Items = 'Item6'
group by Customer

然后你可以将它加入原始表

select  Customer, Items
from    yourTable t1
join    (
            select  Customer, min(DateOfOrder) minDate
            from    yourTable
            where   Items = 'Item6'
            group by Customer
        ) t2
on      t1.Customer = t2.Customer
where   t1.DateOfOrder < t2.minDate