IfNull使用连接问题|大查询

时间:2014-11-18 17:17:54

标签: sql google-bigquery

我需要一些帮助。我有三张表需要我提供信息。最重要的参数是我的表DealID中的Flostream.orders。如果这是null,我希望将其替换为格式相同的Mobileheads.survey.sales_rule

我构建了这个:

SELECT
    filename,
    IFNULL(dealID,mobileheads.surveys.sales_rule) AS DealIDcombo,
    COUNT(*) AS Total,
    SUM(integer(weight)) AS TotalWeight,
    SUM(Productweight)/1000 AS SumWeight,
    Currency,
    Deliverybasecost,
    ROUND(SUM(Deliverybasecost),2) AS TotalDelCost,
    Productsku,
    Productname,
    Dealstartdate
FROM
    [flostream.orders] 
    LEFT OUTER JOIN flostream.briisk 
        ON dealID = Uniquereference
    LEFT OUTER JOIN mobileheads.surveys
        ON mobileheads.surveys.order_number = ExternalReference
GROUP BY 
    filename,
    DealIDCombo,
    currency,
    Deliverybasecost,
    Productname,
    Productsku,
    dealstartdate
ORDER BY
    filename,
    Total desc;

我的问题在于:

LEFT outer JOIN flostream.briisk ON dealID = Uniquereference

理想情况下,我希望它是:

LEFT outer JOIN flostream.briisk ON dealIDCombo = Uniquereference

但不幸的是,这不起作用。

关于如何解决这个问题的任何想法?

1 个答案:

答案 0 :(得分:1)

这是因为连接无法访问在连接后计算的字段。

了解Ifnull如何使用联接表。你需要嵌套这些表。

首先使用mobileheads.surveys加入,然后加入下一个加入。

SELECT * FROM(
  SELECT
    filename,
    IFNULL(dealID,mobileheads.surveys.sales_rule) AS DealIDcombo,
    COUNT(*) AS Total,
    SUM(integer(weight)) AS TotalWeight,
    SUM(Productweight)/1000 AS SumWeight,
    Currency,
    Deliverybasecost,
    ROUND(SUM(Deliverybasecost),2) AS TotalDelCost,
    Productsku,
    Productname,
    Dealstartdate
  FROM
    [flostream.orders]
  LEFT OUTER JOIN mobileheads.surveys
      ON mobileheads.surveys.order_number = ExternalReference) as first
LEFT OUTER JOIN flostream.briisk
    ON first.dealIDCombo = Uniquereference
GROUP BY 
  filename,
  DealIDCombo,
  currency,
  Deliverybasecost,
  Productname,
  Productsku,
  dealstartdate
ORDER BY
   filename,
   Total desc;

原谅一塌糊涂,我不知道这些领域属于哪里。希望这会有所帮助。问我是否需要更多解释!