Question

using the below queries:

Select Count(ID)
FROM Used
Where 
    ID = 54
    AND QTY = 1.875
    AND DateReceived = '2014-03-27 00:00:00'
    AND VendorID = 12400
    AND WithDrawn = 0;


Select Count(ID)
FROM Used
Where 
    ID = 54
    AND QTY = 1.875
    AND DateReceived = '2014-03-27 00:00:00'
    AND VendorID = 12400
    AND WithDrawn = 1;

how can I combine them into one wuery that returns the difference of the counts?

Was it helpful?

Solution

You can just subtract the two values:

SELECT (SELECT COUNT(ID)
        FROM Used
        WHERE ID = 54
          AND QTY = 1.875
          AND DateReceived = '2014-03-27 00:00:00'
          AND VendorID = 12400
          AND WithDrawn = 0) -
       (SELECT COUNT(ID)
        FROM Used
        WHERE ID = 54
          AND QTY = 1.875
          AND DateReceived = '2014-03-27 00:00:00'
          AND VendorID = 12400
          AND WithDrawn = 1);

Alternatively, construct a value of +1 or -1 for each record, and take the sum over that:

SELECT SUM(CASE WithDrawn WHEN 0 THEN 1 ELSE -1 END)
FROM Used
WHERE ID = 54
  AND QTY = 1.875
  AND DateReceived = '2014-03-27 00:00:00'
  AND VendorID = 12400;

OTHER TIPS

Alternatively you could do this in 1 scan...

SELECT 
    (Count(CASE 
    WHEN WithDrawn = 0
        THEN ID END) 
        - 
    Count(CASE 
    WHEN WithDrawn = 1
        THEN ID
    END)) RESULT
FROM Used
WHERE ID = 54
    AND QTY = 1.875
    AND DateReceived = '2014-03-27 00:00:00'
    AND VendorID = 12400;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top