Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtracting alias from another alias?

Tags:

alias

sql

Trying to do some basic math here but can't get this thing to work... I want to compare a counted value based on a set of criteria, and then compare this counted value to the same list of criteria but with one less variable.

 SELECT Testa-TestB FROM(
    (SELECT count(loanflag) AS Testa FROM Data
      WHERE declinegroup="XYZ"
        AND orginalrating="A"
        AND score="724-747"
        AND mode="Open"
        AND delqdays>"0")

    (SELECT count(loanflag) AS Testb FROM Data
      WHERE declinegroup="XYZ"
        AND orginalrating="A"
        AND score="724-747"
        AND mode="Open"))

I think i've been working on this too long and am missing something easy blah!

like image 868
user2540857 Avatar asked Jan 31 '26 16:01

user2540857


1 Answers

In you want direct substraction

in SQL Server

SELECT 
    (
        SELECT count(loanflag) 
        FROM Data
        WHERE 
            declinegroup="XYZ"
            AND orginalrating="A"
            AND score="724-747"
            AND mode="Open"
            AND delqdays>"0"
    ) - (
        SELECT count(loanflag) 
        FROM Data
        WHERE declinegroup="XYZ"
        AND orginalrating="A"
        AND score="724-747"
        AND mode="Open"
    )
;

Alternatively you could assign the values to a variable first then substract them later

DECLARE testa int;
DECLARE testb int;

SET testa = (
        SELECT count(loanflag) 
        FROM Data
        WHERE 
            declinegroup="XYZ"
            AND orginalrating="A"
            AND score="724-747"
            AND mode="Open"
            AND delqdays>"0"
    );

SET testb = (
        SELECT count(loanflag) 
        FROM Data
        WHERE declinegroup="XYZ"
        AND orginalrating="A"
        AND score="724-747"
        AND mode="Open"
    );

Select (testa - testb);
like image 152
Farid Mohd Nor Avatar answered Feb 02 '26 07:02

Farid Mohd Nor