我在面向正确和结构化输出的大查询中运行多个查询

时间:2019-02-19 07:41:08

标签: google-bigquery

我运行查询并在答案编号中得到输出。如果我分部分运行查询,它将返回3行,这是正确的

WITH query AS 
(
   SELECT
       opt.answerNo AS ans,
       task.taskRaised.raisedAt.milliSeconds AS time
   FROM
       Test_2019_02_07
   CROSS JOIN
       UNNEST(task.workflowInfo.answers) AS answer
   CROSS JOIN
       UNNEST(answer.options) AS opt
),
raw AS
(
    SELECT
        COUNTIF(query.ans  = 1 AND query.time BETWEEN 1550341800000 AND 1550341899999) AS ans1
    FROM
        query

    UNION ALL 

    SELECT
        COUNTIF(query.ans = 2 AND query.time BETWEEN 1550341800000 AND 1550341899999) AS ans1 
    FROM
        query

    UNION ALL 

    SELECT
        COUNTIF(query.ans = 3 AND query.time BETWEEN 1550341800000 AND 1550341899999) AS ans1
    FROM
        query 
),
raw1 AS
(
    SELECT
        COUNTIF(query.ans = 1 AND query.time BETWEEN 1548959400000 AND 1550341899999) AS ans2
    FROM
        query 

    UNION ALL 

    SELECT
        COUNTIF(query.ans = 2 AND query.time BETWEEN 1548959400000 AND 1550341899999) AS ans2
    FROM
        query 

    UNION ALL 

    SELECT
        COUNTIF(query.ans = 3 AND query.time BETWEEN 1548959400000 AND 1550341899999) AS ans2
    FROM
        query 
),
raw3 AS
(
    SELECT
        COUNTIF(query.ans = 1 AND query.time BETWEEN 1548959400000 AND 1550514699999) AS ans3
    FROM
        query 

    UNION ALL 

    SELECT
        COUNTIF(query.ans = 2 AND query.time BETWEEN 1548959400000 AND 1550514699999) AS ans3
    FROM
        query

    UNION ALL 

    SELECT
        COUNTIF(query.ans  = 3 AND  query.time BETWEEN 1548959400000 AND 1550514699999) AS ans3
    FROM
        query 
)
SELECT * 
FROM raw, raw1, raw3

我跑步时

SELECT * FROM raw

它将返回

0
0
0

正在运行

SELECT * FROM raw1

返回

1
1
3

并运行

SELECT * FROM raw3

返回

3
1
1

但是当我跑步

SELECT * 
FROM raw, raw1, raw3

它将返回重复编号的27行

我希望

ans1   ans2   ans3
-------------------
  0      1     3
  0      1     1 
  0      3     1

以这种方式,我不明白为什么它会返回27行。

运行此

SELECT * 
FROM raw, raw1, raw3

my output

1 个答案:

答案 0 :(得分:1)

默认情况下,如果我们在选择查询中添加更多表,它将执行cross join

在您的情况下,为了获得预期的输出,我们需要使用联接。由于我们没有任何公共列,因此可以将ROW_NUMBER()添加到所有选择查询中,然后与该列联接。

示例:

with
query1 as (select (ROW_NUMBER() OVER ()) as rn1, id as id1 from table1),
query2 as (select (ROW_NUMBER() OVER ()) as rn2, id as id2 from table2)

select * from query1 join query2 on query1.rn1=query2.rn2