将查询输出格式化为多行

时间:2018-01-12 18:08:36

标签: sql format google-bigquery output

我有以下查询:

#standardsql
WITH TT_bid_info as(
SELECT
DISTINCT
request_id,
revenue_ppc as ppc_avg_TT,
revenue_ppq as ppq_avg_TT
FROM a.quotes
WHERE request_id IN (Select request_id FROM a.quotes WHERE quotes.pro_user_id = 7271495)),

pro_bid_info as(
SELECT
DISTINCT
request_id,
revenue_ppc as ppc_avg_pro,
revenue_ppq as ppq_avg_pro
FROM a.quotes
WHERE request_id IN (Select request_id FROM a.quotes WHERE quotes.pro_user_id = 7271495)
AND pro_user_id = 7271495)

SELECT DISTINCT
round(avg(nullif(TT_bid_info.ppc_avg_TT,0)),2) as ppc_avg_tt,
round(avg(nullif(pro_bid_info.ppc_avg_pro,0)),2) as ppc_avg_pro,
round(avg(nullif(TT_bid_info.ppq_avg_TT,0)),2) as ppq_avg_tt,
round(avg(nullif(pro_bid_info.ppq_avg_pro,0)),2) as ppq_avg_pro
FROM TT_bid_info
JOIN pro_bid_info ON TT_bid_info.request_id = pro_bid_info.request_id

返回:

ppc_avg_tt|ppc_avg_pro|ppq_avg_tt|ppq_avg_pro
22.18     |   6.23    | null     |   4.3

但是,我想要这样的东西:

      TT  | pro
    --------------
ppc|22.18 | 6.23
------------------
ppq|null  | 4.3

我该怎么做呢?我的想法是在"时使用某种情况。功能

1 个答案:

答案 0 :(得分:1)

问题中的查询本身难以剖析,因此我将仅对结果应用我的答案

因此,有很多方法可以将结果中的行转换为几行。以下是几个例子:

   
#standardsql
WITH `yourResult` AS ( 
  SELECT 22.18 ppc_avg_tt, 6.23 ppc_avg_pro, NULL ppq_avg_tt, 4.3 ppq_avg_pro
)
SELECT 'ppc' type, ppc_avg_tt TT, ppc_avg_pro pro FROM `yourResult` UNION ALL
SELECT 'ppq' type, ppq_avg_tt TT, ppq_avg_pro pro FROM `yourResult`    

OR

#standardsql
WITH `yourResult` AS ( 
  SELECT 22.18 ppc_avg_tt, 6.23 ppc_avg_pro, NULL ppq_avg_tt, 4.3 ppq_avg_pro
)
SELECT x.*
FROM `yourResult`, UNNEST([STRUCT<type STRING, TT FLOAT64, pro FLOAT64>
('ppc', ppc_avg_tt, ppc_avg_pro), ('ppq', ppq_avg_tt, ppq_avg_pro)]) x  

两者都以

结果
type    TT      pro  
ppc     22.18   6.23     
ppq     null    4.3  

当然,理想的做法是首先调整您的查询以立即产生所需的结果。希望你能用上面的方法来实现它

与此同时,仍想提出有关您的查询的信息

查询中的片段

  SELECT DISTINCT
    request_id,
    revenue_ppc AS ppc_avg_pro,
    revenue_ppq AS ppq_avg_pro
  FROM `a.quotes`
  WHERE request_id IN (
    SELECT request_id 
    FROM `a.quotes` 
    WHERE pro_user_id = 7271495
  )
  AND pro_user_id = 7271495

相当于以下

  SELECT DISTINCT
    request_id,
    revenue_ppc AS ppc_avg_pro,
    revenue_ppq AS ppq_avg_pro
  FROM `a.quotes`
  WHERE pro_user_id = 7271495

这只是一个例子,可能是因为你(很可能)试图简化你的例子 - 但它很难回答 - 所以这就是为什么我根据你的结果提供答案而不是查询本身< / p>