Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you Divide 2 completely different query results into 1 result

I'm trying to divide the numeric results from 2 pretty different queries.

The end result should be Query 1 DIVIDED BY Query 2

Query 1 =

SELECT COUNT(DISTINCT(table1.ID)) AS count_1
FROM table1 
    INNER JOIN op 
    INNER JOIN Org 
    ON table1.EID = op.id 
        AND Op.OrgID = Org.ID
WHERE table1.TitleID = 123
    AND op.BrandID = 1 
    AND op.Start <= NOW() AND op.End >= NOW();

Query 2 =

SELECT COUNT(DISTINCT user.id) AS count_2
FROM table1 INNER JOIN user INNER JOIN ur
    ON table1.EID = user.id AND ur.userID = user.id
WHERE 
    user.BrandID = 1 
    AND table1.TitleID = 123
    AND ur.role = 0
    AND user.Inactive = 0;
like image 932
Ken Avatar asked Dec 05 '25 20:12

Ken


2 Answers

Sure! You can use subselects to achieve this, though it will be pretty verbose!

SELECT
(
    SELECT COUNT(DISTINCT(table1.ID)) AS count_1
    FROM table1 
        INNER JOIN op 
        INNER JOIN Org 
        ON table1.EID = op.id 
            AND Op.OrgID = Org.ID
    WHERE table1.TitleID = 123
        AND op.BrandID = 1 
        AND op.Start <= NOW() AND op.End >= NOW()
) / (
    SELECT COUNT(DISTINCT user.id) AS count_2
    FROM table1 INNER JOIN user INNER JOIN ur
        ON table1.EID = user.id AND ur.userID = user.id
    WHERE 
        user.BrandID = 1 
        AND table1.TitleID = 123
        AND ur.role = 0
        AND user.Inactive = 0
);

Format however it feels the least ugly to you.

like image 71
Cameron Avatar answered Dec 08 '25 09:12

Cameron


Use sub queries like this:

SELECT Q1.count_1 / Q2.Count_2 
FROM 
( ... Query1 ...) AS Q1
JOIN
( ... Query2 ...) AS Q2
ON 1=1

Replace Query1 and Query2 as your code.

like image 22
sung Avatar answered Dec 08 '25 09:12

sung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!