【问题标题】:AWS Redshift SQL using the results of a query to execute another queryAWS Redshift SQL 使用查询结果执行另一个查询
【发布时间】:2018-09-10 17:43:32
【问题描述】:

我有一张有描述的表格。我正在使用基于作者 ID 的查询来查找相关描述。我使用此代码:

 SELECT
    count(*), h.book_desc
    FROM
    native.authbill p, native.chg h
    where p.book_chg_id = h.book_chg_id
    and 
    (p.aut_key in (
    select aut_key
    from native.authcodes p
    where p.auth_code in (74233, 23421) )
    or p.aut_key in (
    select aut_key
    from native.pubisbn_proc pat
    where isbn_code in ('373423','0256543','0257535')))
    group by h.book_desc

然后我有另一个查询,根据流派查找书籍描述

SELECT
    count(*), h.book_desc
    FROM
    native.authbill p, native.chg h
    where p.book_chg_id = h.book_chg_id
    and p.genre_code in (
    SELECT distinct chg.genre_code
    FROM native.chgset chg
    where chg.genre_desc in ('Sci-fi', 'Action', 'Rom-com')
                        )

我想要做的是从第一个查询中获取所有结果,并通过第二个查询进一步缩小范围。我从第一个查询中得到 150000 个结果,当我运行第二个查询时得到 250000 个结果。如何通过第二个查询缩小第一个查询结果的范围。所以我想使用第一个查询的结果,然后确保这些描述也在流派描述数组中。这是在 AWS Redshift SQL 中。任何帮助表示赞赏。

【问题讨论】:

    标签: sql amazon-redshift


    【解决方案1】:

    您可以使用 CTE 和连接来交叉这两个集合:

    with q1 as (
    SELECT
        count(*) as cnt, h.book_desc
        FROM
        native.authbill p, native.chg h
        where p.book_chg_id = h.book_chg_id
        and 
        (p.aut_key in (
        select aut_key
        from native.authcodes p
        where p.auth_code in (74233, 23421) )
        or p.aut_key in (
        select aut_key
        from native.pubisbn_proc pat
        where isbn_code in ('373423','0256543','0257535')))
        group by h.book_desc
    ),
    q2 as (
    SELECT
        count(*) as cnt, h.book_desc
        FROM
        native.authbill p, native.chg h
        where p.book_chg_id = h.book_chg_id
        and p.genre_code in (
        SELECT distinct chg.genre_code
        FROM native.chgset chg
        where chg.genre_desc in ('Sci-fi', 'Action', 'Rom-com')
                            )
    )
    select book_desc, q1.cnt, q2.cnt 
    from q1 join q2 using book_desc
    

    【讨论】:

      【解决方案2】:

      我认为您可以在where 子句中使用and 条件:

      select count(*), h.book_desc
      from native.authbill p join
           native.chg h
           on p.book_chg_id = h.book_chg_id
      where (p.aut_key in (select aut_key
                           from native.authcodes p
                           where p.auth_code in (74233, 23421)
                          ) or
             p.aut_key in (select aut_key
                           from native.pubisbn_proc pat
                           where isbn_code in ('373423', '0256543', '0257535')
                          )
            ) and
            p.genre_code in (select chg.genre_code
                             from native.chgset chg
                             where chg.genre_desc in ('Sci-fi', 'Action', 'Rom-com')
                            ) 
      group by h.book_desc;
      

      【讨论】:

        最近更新 更多