2017-04-03 1 views
0

Je suis nouveau à SAS, mais sais SQL alors en essayant d'utiliser le code SQL pour écrire le code proc sql et réalisé que PARTITION by n'est pas disponible dans SAS.SQL à PROC SQL-partition Par alternative (min cas)

Tableau

Customer_id Item_type Order Size Date  …. 

1. A401 Fruit   Small  3/14/2016 …. 
2. A401 Fruit   Big  5/22/2016 …. 
3. A401 Vegetable  Small  7/12/2016 …. 
4. B509 Vegetable  Small  3/25/2015 …. 
5. B509 Vegetable  Big  3/15/2014 …. 
6. B509 Vegetable  Small  3/1/2014  …. 

Explication

Customer_id Item_Type Count  Reason 
1.A401   Fruit  2   X-WRONG-because date corresponding big item is later than others in group 
2.B509   Vegetable 2   RIGHT-Note that count is 2 only because one of the dates is earlier than the Big corresponding item(3/1/2014 is earlier than 3/15/2014) 

Sortie SQL

Customer_id Item_Type Count  
1.B509   Vegetable  2 
select t.customer_id, t.item_type, count(*) 
from (select t.*, 
     min(case when OrderSize = 'Big' then date end) over (partition by customer_id, item_type) as min_big 
    from t 
) t 
where date > min_big 
group by t.customer_id, t.item_type; 

Répondre

1

Dans les dialectes SQL (MS Access, MySQL, SQLite, SQL proc SAS) qui ne ne supporte pas la fonction de fenêtre ns, la plupart des appels PARTITION BY peuvent être remplacés par des sous-requêtes agrégées corrélées, ce qui est supporté par tous les principaux dialectes SQL. Tenez compte de l'ajustement suivant:

select main.customer_id, main.item_type, count(*) as count 
from 
    (select t.customer_id, t.item_type, t.date, 
      (select min(case when OrderSize = 'Big' then date end) 
      from t sub 
      where sub.customer_id = t.customer_id 
      and sub.item_type = t.item_type) as min_big 
    from t 
    ) main 
where main.date > main.min_big 
group by main.customer_id, main.item_type; 
+0

get main.date n'existe pas d'erreur. – viji

+0

Oups! Voir éditer. Ajoutez * date * dans 'SELECT 'de la table dérivée. En remplaçant votre astérisque, j'oublie d'inclure ce type important. – Parfait