如何按月迭代bigquery代码?

时间:2017-10-28 07:08:11

标签: sql google-bigquery tableau

我想以月为单位迭代以下代码,这样我就可以为每个月下线的月度数据制作一个tableau信息中心:

SELECT
    Deal_ID,
    Category,
    MONTH(date),
    YEAR(date)
FROM [big-query-1233:BI_Automation.live_deals_history_since_15_sep] 
WHERE
    MONTH(date) = 4 AND
    Deal_ID NOT IN (
        SELECT Deal_id
        FROM [big-query-1233:BI_Automation.live_deals_history_since_15_sep]  
        WHERE MONTH(date) = 5
    )

2 个答案:

答案 0 :(得分:2)

下面是BigQuery Standard SQL,避免使用JOIN而是使用分析函数

  
#standardSQL
SELECT
  Deal_ID, Category, 
  EXTRACT(MONTH FROM month) AS month,
  EXTRACT(YEAR FROM month) AS year  
FROM (
  SELECT
    Deal_ID, Category, month,
    LEAD(month) OVER(PARTITION BY Deal_ID, Category ORDER BY month) AS next_month
  FROM (
    SELECT
      Deal_ID, Category,
      DATE_TRUNC(DATE, MONTH) month
    FROM `big-query-1233.BI_Automation.live_deals_history_since_15_sep` 
    GROUP BY Deal_ID, Category, month
  )
)
WHERE DATE_DIFF(next_month, month, MONTH) > 1
-- ORDER BY month, Deal_ID, Category  

您可以使用以下虚拟数据

进行测试/播放
#standardSQL
WITH `big-query-1233.BI_Automation.live_deals_history_since_15_sep` AS (
  SELECT 1 AS Deal_ID, 1 AS Category, DATE '2017-01-01' AS DATE UNION ALL
  SELECT 1, 1, DATE '2017-01-02' UNION ALL
  SELECT 1, 1, DATE '2017-02-02' UNION ALL
  SELECT 1, 1, DATE '2017-02-15' UNION ALL
  SELECT 1, 1, DATE '2017-03-15' UNION ALL
  SELECT 1, 1, DATE '2017-04-15' UNION ALL
  SELECT 1, 1, DATE '2017-06-15' UNION ALL
  SELECT 1, 1, DATE '2017-07-07' UNION ALL
  SELECT 1, 1, DATE '2017-08-22' UNION ALL
  SELECT 1, 1, DATE '2017-12-12' 
)
SELECT
  Deal_ID, Category, 
  EXTRACT(MONTH FROM month) AS month,
  EXTRACT(YEAR FROM month) AS year  
FROM (
  SELECT
    Deal_ID, Category, month,
    LEAD(month) OVER(PARTITION BY Deal_ID, Category ORDER BY month) AS next_month
  FROM (
    SELECT
      Deal_ID, Category,
      DATE_TRUNC(DATE, MONTH) month
    FROM `big-query-1233.BI_Automation.live_deals_history_since_15_sep` 
    GROUP BY Deal_ID, Category, month
  )
)
WHERE DATE_DIFF(next_month, month, MONTH) > 1
ORDER BY month, Deal_ID, Category    

注意:目前尚不清楚您是需要COUNT个客户还是只需要客户列表 上面给出了清单
但是如果你需要COUNTs - 你只需添加额外的GROUP BY和COUNT,因为它在下面

#standardSQL
SELECT
  Category, 
  EXTRACT(MONTH FROM month) AS month,
  EXTRACT(YEAR FROM month) AS year,  
  COUNT(Deal_ID) AS customers
FROM (
  SELECT
    Deal_ID, Category, month,
    LEAD(month) OVER(PARTITION BY Deal_ID, Category ORDER BY month) AS next_month
  FROM (
    SELECT
      Deal_ID, Category,
      DATE_TRUNC(DATE, MONTH) month
    FROM `big-query-1233.BI_Automation.live_deals_history_since_15_sep` 
    GROUP BY Deal_ID, Category, month
  )
)
WHERE DATE_DIFF(next_month, month, MONTH) > 1
GROUP BY month, year, Category
ORDER BY month, year, Category  

答案 1 :(得分:0)

希望这有助于您入门。请注意,它使用标准SQL而不是BigQuery的旧SQL:

img