我有下表
cust_id | category | counts
1 | food | 2
1 | pets | 5
3 | pets | 3
我想得到這個輸出
cust_id | food_count | pets_count
1 | 2 | 5
3 | 0 | 3
其中列數映射列中的所有唯一值category。你知道如何在 Presto SQL 中做到這一點嗎?如果我在 pySpark 中執行此操作,我會使用 CountVectorizer,但我對 SQL 有點吃力。
uj5u.com熱心網友回復:
您可以使用 GROUP BY 并根據條件求和。例如使用if函式:
-- sample data
WITH dataset (cust_id, category, counts) AS (
VALUES (1, 'food', 2),
(1, 'pets', 5),
(3, 'pets', 3)
)
--query
select cust_id, sum(if(category = 'food', counts, 0)) food_counts, sum(if(category = 'pets', counts, 0)) pets_counts
from dataset
group by cust_id
輸出:
| cust_id | food_counts | pets_counts |
|---|---|---|
| 1 | 2 | 5 |
| 3 | 0 | 3 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/413576.html
標籤:
