2016-11-21 6 views
0

Stellen Sie sich vor, ich habe eine Tabelle auf Redshift mit dieser ähnlichen Struktur. Product_Bill_ID ist der Primärschlüssel dieser Tabelle.Redshift Count mit Variable

| Store_ID | Product_Bill_ID | Payment_Date  
| 1  | 1    | 01/10/2016 11:49:33  
| 1  | 2    | 01/10/2016 12:38:56  
| 1  | 3    | 01/10/2016 12:55:02  
| 2  | 4    | 01/10/2016 16:25:05  
| 2  | 5    | 02/10/2016 08:02:28  
| 3  | 6    | 03/10/2016 02:32:09 

Wenn ich die Anzahl der Product_Bill_ID, dass ein Geschäft in der ersten Stunde verkauft abfragen will, nachdem er seine erste Product_Bill_ID verkauft, wie könnte ich das tun?

Dieses Beispiel sollte Ergebnis

| Store_ID | First_Payment_Date | Sold_First_Hour  
| 1  | 01/10/2016 11:49:33 | 2     
| 2  | 01/10/2016 16:25:05 | 1      
| 3  | 03/10/2016 02:32:09 | 1     

Antwort

0

Sie müssen die erste Stunde zu erhalten. Das ist leicht genug, um mit Fensterfunktionen:

select s.*, 
     min(payment_date) over (partition by store_id) as first_payment_date 
    from sales s 

Dann müssen Sie das Datum Filterung und Aggregation tun:

select store_id, count(*) 
from (select s.*, 
      min(payment_date) over (partition by store_id) as first_payment_date 
     from sales s 
    ) s 
where payment_date <= first_payment_date + interval '1 hour' 
group by store_id; 
0
SELECT 
    store_id, 
    first_payment_date, 
    SUM(
     CASE WHEN payment_date < DATEADD(hour, 1, first_payment_date) THEN 1 END 
    ) AS sold_first_hour 
FROM 
(
    SELECT 
     *, 
     MIN(payment_date) OVER (PARTITION BY store_id) AS first_payment_date 
    FROM 
     yourtable 
) 
    parsed_table 
GROUP BY 
    store_id, 
    first_payment_date