简体   繁体   中英

SQL Query, subquery minus subquery?

Ok, so Ive been trying to get this query working for hours now, but nothing I seem to do will get me the results I am after.

SELECT COALESCE(SUM(ps.cost), 0) AS ps_total
FROM Customers c
    LEFT JOIN ProductSales ps ON c.customer_ID = ps.customer_ID
GROUP BY c.sex;

SELECT COALESCE(SUM(hc.cost), 0) AS hc_total
FROM Customers c
    LEFT JOIN HairCuts hc ON c.customer_ID = hc.customer_ID
GROUP BY c.sex;

So the above two queries work fine. Each one finds the total spent on either products or hair cuts and groups by gener thus giving me the total spent on cuts and products for males and females individually.However somehow I need to combine these in such a way that I can display the gender(s) that spent more on products than on haircuts.

Any help with this would be very much appreciated.

PS hopefully the question is clear enough. If not Ill try to elaborate.

Another way you can join your both query results as

SELECT  t1.sex,
COALESCE(t1.ps_total - t2.hc_total,0)  AS `difference`
FROM 
(SELECT COALESCE(SUM(ps.cost), 0) AS ps_total ,c.sex
FROM Customers c
    LEFT JOIN ProductSales ps ON c.customer_ID = ps.customer_ID
GROUP BY c.sex) t1
LEFT JOIN 
(SELECT COALESCE(SUM(hc.cost), 0) AS hc_total ,c.sex
FROM Customers c
    LEFT JOIN HairCuts hc ON c.customer_ID = hc.customer_ID
GROUP BY c.sex) t2
USING(sex)
HAVING difference > 0

Edit from comments

I have used a short syntax for ON() clause like USING(sex) = ON(t1.sex=t2.sex) if you have a same name for a column in both tables you can use USING() if you have different then you need to use ON() syntax

Like

Table1 column(category_id primary key,...)

Table2 column(category_id foreign key,...)

Then you can easily use USING()

SELECT * FROM
Table1 
JOIN Table2 
USING(category_id )

But if you have different name for association then you need to use ON() clause

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