avi
avi

Reputation: 1846

difference query between two tables in Postgresql?

In Postgresql I have table of items as follow:

id  qty 
1    20
2    45
3    10

it contains the quantity of each product. I'm doing a counting operation. For every item I count I copy the data to a a log_count table. Items table NEVER CHANGED.

I want to write a query which will show me the difference between the tables. Basically how much left to pass over. When the quantity is 0 the row disappears.

This is how it should be:

Start:

items:             log_count:              QUERY SHOW:
    1    20                                1        20
    2    45                                2        45
    3    10                                3        10

after doing count of: id=1 qty=3

items:             log_count:              QUERY SHOW:
    1    20         1      3               1        17
    2    45                                2        45
    3    10                                3        10

later, after doing count of: id=2 qty=45

items:             log_count:              QUERY SHOW:
    1    20         1      3               1        17
    2    45         2      45              3        10
    3    10                                * row of id 2 is gone as its qty=0

later, after doing count of: id=1 qty=2

items:             log_count:              QUERY SHOW:
    1    20         1      5               1        15
    2    45         2      45              3        10
    3    10                               

Final stage...

items:             log_count:              QUERY SHOW:
    1    20         1      20             
    2    45         2      45             
    3    10         3      10                      

How do I write this query?

Upvotes: 0

Views: 1356

Answers (1)

user330315
user330315

Reputation:

Looks like a simple join to me:

select it.id, it.qty - lc.qty as difference
from items it
  left join log_count lc on it.id = lc.id 
where it.qty - lc.qty > 0;

Upvotes: 1

Related Questions