简体   繁体   中英

SQL query to find comparision between different products

Hi i am a newbie to SQL and have one doubt on comparing different products across multiple tables. I have 3 tables

T1: Product_type order_id

T2 and T3 also has the same fields.

All the tables have different product types. They may or may not have same order ids. Its like you can order product p1 from T1 and product p2 from T2 together on the same order id o1 or they can be separate orders.

I want to find the number of orders where product type(p1) from T1 and product type(p2) from T2 are ordered in the same order(having the same order id).

I am trying to run the query like this :

select COUNT(DISTINCT order_id) as CountOf from
(
    select product_type from t1
    UNION ALL select product_type from t2
)
AS m
where t1.product_type = p1 and t2.product_type = p2;

What i figured out is that i cannot access t1 and t2 in the outer query since they are used in the inner query. So is there a way i can make comparision between products? Any help would be greatly appreciated. Thank you

Try this:

select
    count(distinct t1.order_id) as OrderCount
from
    t1
    inner join
    t2 on t1.order_id = t2.order_id
where
    t1.product_type = 'p1' and
    t2.product_type = 'p2'

I can't understand what you want. But inner query scope to brackets only. So you can not access outside to brackets. try to this

select COUNT(DISTINCT order_id) as CountOf from
(
    select DISTINCT order_id from t1
    where t1.product_type = p1
    UNION ALL 
    select DISTINCT order_id from t2
    where t2.product_type = p2
) m

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM