[英]SQL first date for the first specific occurrence of a value
假設我有一個如下表:
msg.tracking_number | msg.subtag_Message | msg.checkpoint_time |
---|---|---|
12345678 | 發表 | 2022-05-12 |
12345678 | 在途中 | 2022-05-11 |
12345678 | 在途中 | 2022-05-10 |
12345678 | 在途中 | 2022-05-09 |
12345678 | 在途中 | 2022-05-08 |
12345678 | 收到信息 | 2022-05-07 |
87654321 | 發表 | 2022-05-06 |
87654321 | 在途中 | 2022-05-05 |
87654321 | 在途中 | 2022-05-04 |
87654321 | 在途中 | 2022-05-03 |
87654321 | 收到信息 | 2022-05-02 |
87654321 | 收到信息 | 2022-05-01 |
在中間,您會看到標簽。 “收到的信息”始終與給定跟蹤號的最早日期相關。 收到的信息量總是可變的。 大多數情況下,每個跟蹤號只收到一個信息,其他時候不止一個。
我想要的是與“在途”標簽相關的日期。 具體來說,是“在途”中的最早 (MIN) 日期。
我已經嘗試了以下方法:
SELECT
A.checkpoint_time,
msg.subtag_message,
msg.tracking_number,
Case
When
msg.subtag_message = 'In Transit'
Then A.checkpoint_time
End as test
FROM `reporting-01.aftership.aftership_data`, UNNEST(msg.checkpoints) as A
但是,這給了我與在途標簽相關的所有日期。 同樣,與一個跟蹤號相關的在途數量是可變的。 大部分是 3 個,但可以更多。 我在想我必須在一個 CASE 中構建一個 CASE,它只給我一個,MIN,在運輸日期......但我不知道如何定義這個語法......
環境是一個LOOKER SQL runner數據庫,原始數據來自GBQ。
有任何想法嗎?
對 tracking_number 和 subtag_Message 的每個組合的每個 checkpoint_time 應用排名,並根據 subtag_Message 和計算的排名應用過濾器
WITH ranked_table AS (
SELECT *, RANK() OVER (PARTITION BY tracking_number, subtag_Message ORDER BY checkpoint_time) AS cp_rank
FROM table1
)
SELECT * EXCEPT(cp_rank)
FROM ranked_table
WHERE subtag_Message != "Info Received" OR cp_rank = 1
追蹤號碼 | subtag_Message | checkpoint_time |
---|---|---|
12345678 | 發表 | 2022-05-12 |
12345678 | 在途中 | 2022-05-11 |
12345678 | 在途中 | 2022-05-10 |
12345678 | 在途中 | 2022-05-09 |
12345678 | 在途中 | 2022-05-08 |
12345678 | 收到信息 | 2022-05-07 |
87654321 | 發表 | 2022-05-06 |
87654321 | 在途中 | 2022-05-05 |
87654321 | 在途中 | 2022-05-04 |
87654321 | 在途中 | 2022-05-03 |
87654321 | 收到信息 | 2022-05-01 |
您應該按tracking_number
和subtag_message
:
SELECT
msg.tracking_number,
msg.subtag_message,
MIN(A.checkpoint_time) AS checkpoint_time
FROM `reporting-01.aftership.aftership_data`, UNNEST(msg.checkpoints) as A
WHERE msg.subtag_message = 'In Transit'
GROUP BY msg.tracking_number, msg.subtag_message
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.