-6

How can I calculate the difference between the purchase and sale quantity in one query using Ms Access database?

My data, for example, looks like this:

ProductId Type Quantity
1         Purchase 24
1         Sale      1

How would I get the difference of (24-1=23) in one query?

Johnny Bones
  • 8,786
  • 7
  • 52
  • 117
user2674803
  • 15
  • 1
  • 3

2 Answers2

0

You can self-join the table:

SELECT p.productId, (p.quanity - COALESCE(s.quantity, 0)) difference
FROM table p
LEFT JOIN table s
ON p.type = 'Purchase' AND s.type = 'Sale' AND p.productId = s.productId
knittl
  • 246,190
  • 53
  • 318
  • 364
0

I suppose you have the database name [DB-NAME]. and Columns and rows are something like.

[Table1]
ProductID      Quantity         Purchase         Sale
-----------    ---------        ---------        --------
1                1                 24              1
2                100               50              10

If you want to calculate the [Purchase] - [Sale] for a specific Product id Use:

( Select (Purchase - Sale) AS MyNumber FROM[DB-Name].[Table1] WHERE (ProductID=1))

//where 1 is your product id

The result table will be

MyNumber
--------
23

if you want to calculate the totals for all [ProductID] Use:

  (Select (SUM(Purchase) - Sum(Sale)) AS MyNumber FROM[DB-Name].[Table1] )

The result table will be

MyNumber
--------
63
NuminousName
  • 200
  • 1
  • 15