下面是BigQuery的標準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
注:目前尚不清楚,如果你需要的客戶數量或客戶只是名單 上面給你列出
但是如果你需要計數 - 你只需要添加額外的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
你GROUP BY聚集是沒有意義的,因爲你在沒有任何聚合函數您選擇條款。 –
是的,這是一個愚蠢的錯誤 –
也許你應該告訴我們你在這裏試圖做什麼。 –