我有一个如下表,其中显示了产品的购物车
每个id都有不同的产品,例如:id 1有3个产品,id 2有4 ...但是每个ID的最大产品数是10。时间戳记以DESC排序。所以现在我想像这样转换这张表:
表的模式:
我在Pivot Repeated fields in BigQuery处尝试了解决方案,但是列数太多。我怎样才能有最多与10个产品对应的新列
谢谢
答案 0 :(得分:3)
以下选项适用于BigQuery标准SQL
#standardSQL
SELECT id,
products[SAFE_OFFSET(0)].product_id product_id_1,
products[SAFE_OFFSET(0)].price price_1,
products[SAFE_OFFSET(1)].product_id product_id_2,
products[SAFE_OFFSET(1)].price price_2,
products[SAFE_OFFSET(2)].product_id product_id_3,
products[SAFE_OFFSET(2)].price price_3,
products[SAFE_OFFSET(3)].product_id product_id_4,
products[SAFE_OFFSET(3)].price price_4,
products[SAFE_OFFSET(4)].product_id product_id_5,
products[SAFE_OFFSET(4)].price price_5,
products[SAFE_OFFSET(5)].product_id product_id_6,
products[SAFE_OFFSET(5)].price price_6,
products[SAFE_OFFSET(6)].product_id product_id_7,
products[SAFE_OFFSET(6)].price price_7,
products[SAFE_OFFSET(7)].product_id product_id_8,
products[SAFE_OFFSET(7)].price price_8,
products[SAFE_OFFSET(8)].product_id product_id_9,
products[SAFE_OFFSET(8)].price price_9,
products[SAFE_OFFSET(9)].product_id product_id_10,
products[SAFE_OFFSET(9)].price price_10
FROM `project.dataset.table`
或
#standardSQL
SELECT id,
MAX(IF(off = 0, product_id, NULL)) product_id_1,
MAX(IF(off = 0, price, NULL)) price_1,
MAX(IF(off = 1, product_id, NULL)) product_id_2,
MAX(IF(off = 1, price, NULL)) price_2,
MAX(IF(off = 2, product_id, NULL)) product_id_3,
MAX(IF(off = 2, price, NULL)) price_3,
MAX(IF(off = 3, product_id, NULL)) product_id_4,
MAX(IF(off = 3, price, NULL)) price_4,
MAX(IF(off = 4, product_id, NULL)) product_id_5,
MAX(IF(off = 4, price, NULL)) price_5,
MAX(IF(off = 5, product_id, NULL)) product_id_6,
MAX(IF(off = 5, price, NULL)) price_6,
MAX(IF(off = 6, product_id, NULL)) product_id_7,
MAX(IF(off = 6, price, NULL)) price_7,
MAX(IF(off = 7, product_id, NULL)) product_id_8,
MAX(IF(off = 7, price, NULL)) price_8,
MAX(IF(off = 8, product_id, NULL)) product_id_9,
MAX(IF(off = 8, price, NULL)) price_9,
MAX(IF(off = 9, product_id, NULL)) product_id_10,
MAX(IF(off = 9, price, NULL)) price_10
FROM `project.dataset.table`,
UNNEST(products) product WITH OFFSET off
GROUP BY id