[英]Select value ordered by another value in same table without sub-query
我在 GBQ 上使用 SQL。
我有一個包含以下列的表格:
標題編號 | 標題 | ID |
---|---|---|
1 | H:A:F | 1 |
2 | R:V:G | 1 |
1 | v234 | 2 |
2 | B:N:E | 2 |
3 | R:V:G | 2 |
我寫了一個查詢,為每個ID
選擇:第一個title
(按titlenum
)。
SELECT MAX(CASE WHEN CAST(titlenum AS INT64 ) = 1 THEN title END) AS first_title
FROM `table`
GROUP BY ID
這將返回以下結果:
標題編號 | 標題 | ID |
---|---|---|
1 | H:A:F | 1 |
1 | v234 | 2 |
PS:這個SELECT
查詢是一個更大的查詢的一部分,它選擇了更多的列。
我需要在我的查詢中添加另一個條件:我想 select titlenum
值最小的標題,它的值也至少有一個“:”。
所以理想情況下我想要這個結果:
標題編號 | 標題 | ID |
---|---|---|
1 | H:A:F | 1 |
2 | B:N:E | 2 |
我可以做一個子查詢,然后在原始查詢中使用first_title
列:
SELECT MIN(title) as first_title, ID
FROM `table`
WHERE title like '%:%'
GROUP BY ID
但是有沒有“更好”的方法呢? 我可以使用CASE
WHEN
代替子查詢嗎? 原始查詢已經太大,我想避免向其中添加另一個子查詢。
在 BigQuery 中,一種方法是聚合:
select (array_agg(t order by titlenum limit 1))
from `table` t
group by id;
這將返回整行。 如果這是您真正想要的,您可以只使用 select 標題:
select id, (array_agg(t.title order by titlenum limit 1))[ordinal(1)] as title
[ordinal(1)].* from table
t group by id;
但是,根據您的編號,您是否只想過濾:
select t.*
from `table` t
where titlenum = 1;
通常ARRAY_AGG用於 BigQuery 中的此類情況:
with `table` as (
select 1 as titlenum, 'H:A:F' as title, 1 as id union all
select 2, 'R:V:G', 1 union all
select 1, 'v234', 2 union all
select 2, 'B:N:E', 2 union all
select 3, 'R:V:G', 2
)
select ARRAY_AGG(STRUCT(titlenum, title) ORDER BY titlenum)[OFFSET(0)].*, id
from `table`
where title like '%:%'
group by id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.