2017-04-06 3 views
2

Ich möchte eine berechnete Spalte in einer großen Abfrage erstellen, die Folgendes macht:Berechnete Spalte, um fehlende IDs zu füllen

Ich habe Tabelle mit Produkt-ID und Produktsegment-ID. Aber die Produktsegmentwerte fehlen teilweise. Daher würde Ich mag eine weitere Spalte „ProdSed ID Calc“ schaffen, in dem die fehlenden Produktsegment IDs „ProdSeg ID“, wie unten dargestellt gefüllt sind:

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

mir Könnte jemand helfen?

Mit freundlichen Grüßen Albertok

Antwort

0

In BigQuery möchten Sie wahrscheinlich die Tabelle nicht wirklich aktualisieren. Stattdessen können Sie sie schnell erzeugen mit:

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

Sie diese Logik in eine Sicht setzen und die Aussicht abfragen.

+0

Vielen Dank für Ihre Hilfe. Die Lösung von Gordon hat mir gut getan. – Albertok

+0

Mit freundlichen Grüßen Albrecht – Albertok

0

Wenn Sie die Original-Tabelle zu aktualisieren:

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 ) 

Wenn Sie tun, was Sie gefragt:

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 ) 

Aber Vorsicht hier machen sicher, die ProdSeg ID (nicht null diejenigen) für die eine Product ID ist einzigartig.

0

Versuchen Sie unten für 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 

Sie testen/mit ihm spielen Dummy-Daten aus Ihrer Frage mit:

#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 

Hinweis: mich persönlich - ich würde mit der Verwendung Analytic Functions wie es in Gordons Antwort vorgeschlagen wird. Aber wollte dir mehr Möglichkeiten geben - je nachdem, wie dein echter Anwendungsfall ist, kann es mehr oder weniger nützlich sein

Verwandte Themen