2017-04-06 60 views
2

我想在大查询中创建一个计算列,它执行以下操作:计算栏填写缺失ID

我有带产品ID和产品段ID的表。但产品细分价值部分缺失。因此,我想创建如下图所示的另一列“ProdSed ID计算器”,其中丢失的产品段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

在BigQuery中,您可能不想实际更新表格。相反,您可以使用动态生成它们:

select t.*, 
     max(ProdSegID) over (partition by ProductId) as ProdSedID_Calc 
from t; 

你可以把这个逻辑嵌入一个视图,查询视图。下面

+0

谢谢大家的帮助。戈登的解决方案为我工作得很好。 – Albertok

+0

亲切的问候 Albrecht – Albertok

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(非空字符)为Product ID唯一

0

尝试使用BigQuery的标准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,正如Gordon的答案中所建议的那样。但想给你更多的选择 - 取决于你的实际使用情况,它可能或多或少有用