如何仅按a列中具有b列中所有值的id进行过滤

时间:2019-11-30 14:15:10

标签: sql presto

我能否请我提供一些指导,以指导我如何仅通过b列中具有所有值的值(来自a列)来过滤Presto SQL?

因此,我希望在promotion_running_days列中按日期获取具有所有促销日(从1到9)的所有product_id。

我尝试在(1,2,3,4,5,6,7)中使用'promotion_running_days,但它也返回product_id仅具有2或3促销日的产品。

使用这种查询方法:

SELECT
    product_id
    ,date
    ,ROUND(MAX(DATE_DIFF('day', CAST(DATE_PARSE(promotion_start_date, '%Y-%m-%d %T') AS DATE), CAST(DATE_PARSE(date, '%Y-%m-%d') AS DATE))),0) AS promotion_running_days
    ,SUM(revenue) AS total_revenue    
FROM product_db 
 WHERE
        date  between '2019-01-01' and '2019-01-07' 
        AND promotion_start_date>='2019-01-01' 
Group by 1,2;

我希望我的输出看起来像这样:

Product Id  |Date|       |Promotion Running Days|

1          |2019-01-01|    |1|
1          |2019-01-02|    |2|
1          |2019-01-03|    |3|
1          |2019-01-04|    |4|
1          |2019-01-05|    |5|
1          |2019-01-06|    |6|
1          |2019-01-07|    |7|

1 个答案:

答案 0 :(得分:0)

  

我希望按日期获得所有促销日的所有product_id

您似乎想要聚合。假设每个日期最多有一行:

SELECT product_id, SUM(revenue) AS total_revenue    
FROM product_db 
WHERE date  between '2019-01-01' and '2019-01-07' and
      promotion_start_date>='2019-01-01' 
GROUP BY product_id
HAVING COUNT(*) = 7;  -- 7 == all days

但是,您的示例结果建议row_number()

select product_id, date,
       row_number() over (partition by product_id order by date)
from product_db
order by product_id, date;