Reputation: 129
I have a table that has descriptions. I am using a query based on author IDs to find the relevant descriptions. I use this code:
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
Then I have a another query that finds book descriptions based on a genre
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')
)
What I want to do is take all the results from the first query and narrow them down further by the second query. I get 150000 results from the first query and 250000 when i run the second query. How can I narrow down the first query results by the second query. So I want to use the results from the first query and then make sure those descriptions also are in the genre description array. This is in AWS Redshift SQL. Any help is appreciated.
Upvotes: 0
Views: 756
Reputation: 1269463
I think you can just use an and
condition in the where
clause:
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;
Upvotes: 0
Reputation: 9687
You could use a CTE, and a join to intersect the two sets:
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
Upvotes: 2