2017-04-06 76 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的答案中所建議的那樣。但想給你更多的選擇 - 取決於你的實際使用情況,它可能或多或少有用