我想在Big Query中创建一个计算列,它执行以下操作:
我有包含产品ID和产品细分ID的表格。但产品部分价值部分缺失。因此,我想创建另一列“ProdSed ID Calc”,其中缺少产品段ID“ProdSeg ID”,如下所示:
Product ID ProdSeg ID ProdSed ID Calc
1 1 1
1 Null 1
1 Null 1
2 Null 5
2 5 5
2 5 5
3 Null 18
3 Null 18
3 18 18
有人可以帮助我吗?
亲切的问候 Albertok
答案 0 :(得分:0)
如果您需要更新原始表:
UPDATE Your_Table as A
SET ProdSegID =
(Select [ProdSeg ID]
FROM Your_Table as B
Where B.Product ID = A.Product ID and [ProdSeg ID] is not null )
如果你需要做你所问的:
UPDATE Your_Table as A
SET [ProdSed ID Calc] =
(Select [ProdSeg ID]
FROM Your_Table as B
Where B.Product ID = A.Product ID and [ProdSeg ID] is not null )
但请注意,请确保ProdSeg ID
的{{1}}(非空的)唯一。
答案 1 :(得分:0)
在BigQuery中,您可能不希望实际更新表。相反,您可以使用以下方式生成它们:
select t.*,
max(ProdSegID) over (partition by ProductId) as ProdSedID_Calc
from t;
您可以将此逻辑放入视图中并查询视图。
答案 2 :(得分:0)
在下面尝试BigQuery Standard SQL
#standardSQL
WITH segments AS (
SELECT ProductID, MAX(ProdSegID) AS ProdSegIDCalc
FROM yourTable
GROUP BY ProductID
)
SELECT t.ProductID, t.ProdSegID, s.ProdSegIDCalc
FROM yourTable AS t
JOIN segments AS s
ON t.ProductID = s.ProductID
ORDER BY ProductID
您可以使用问题中的虚拟数据进行测试/播放:
#standardSQL
WITH yourTable AS (
SELECT 1 AS ProductID, 1 AS ProdSegID UNION ALL
SELECT 1, NULL UNION ALL
SELECT 1, NULL UNION ALL
SELECT 2, NULL UNION ALL
SELECT 2, 5 UNION ALL
SELECT 2, 5 UNION ALL
SELECT 3, NULL UNION ALL
SELECT 3, NULL UNION ALL
SELECT 3, 18
),
segments AS (
SELECT ProductID, MAX(ProdSegID) AS ProdSegIDCalc
FROM yourTable
GROUP BY ProductID
)
SELECT t.ProductID, t.ProdSegID, s.ProdSegIDCalc
FROM yourTable AS t
JOIN segments AS s
ON t.ProductID = s.ProductID
ORDER BY ProductID
注意:我个人 - 我会按照戈登的回答建议使用Analytic Functions
。但是想给你更多的选择 - 根据你的实际用例,它可能或多或少有用