2017-04-05 178 views
0

這裏的秩序日期前訂購的表我有項目的特定項目

|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表不應該有項6的信息!

任何建議將非常感謝!

回答

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'); 
+0

謝謝CL!我懂了邏輯! – Sai

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 
+0

謝謝Stefano!它非常整潔! – Sai