tags:

views:

81

answers:

4

this statement will generate a 4 column table:

SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate,
        'Delivery' AS Legend, -price*quantity AS amount
    FROM product JOIN shipped ON (product.id = shipped.product)
UNION
  SELECT receipt.badguy, receipt.rdate,notes, amount
  FROM receipt

how do i get the total sum of the 4th of column of what the above generates?

+1  A: 
SUM(-price*quantity)

huh?

zerkms
+1  A: 

Try

sum(price*quantity)

or combine both query as

SELECT badguy,rdate,notes,SUM(AMOUNT) FROM(
        SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate, 
        'Delivery' AS Legend, -price*quantity AS amount 
    FROM product JOIN shipped ON (product.id = shipped.product) 
UNION 
  SELECT receipt.badguy, receipt.rdate,notes, amount 
  FROM) A
Saif Khan
+1  A: 

I like to use subqueries for everything.

SELECT SUM(results.amount)
FROM
(
SELECT -price*quantity AS amount 
    FROM product JOIN shipped ON (product.id = shipped.product) 
UNION 
  SELECT amount 
  FROM  
...
) results
Jeffrey L Whitledge
sql: errorEvery derived table must have its own aliasnumber: 1248
I__
Oh, yeah, you'll need an alias for the subquery. I'll add it.
Jeffrey L Whitledge
In Oracle, subquery expressions do not require aliases. `select count(dummy) from (select * from dual);` is perfectly valid.
Adam Musch
+1  A: 

Wrap your query in another query, where the outer query just gets the sum you want. This makes your query a subquery.

SELECT SUM(amount) FROM (
   SELECT shipped.badguy AS badguy, shipped.sdate AS LineDate,
           'Delivery' AS Legend, -price*quantity AS amount
       FROM product JOIN shipped ON (product.id = shipped.product)
   UNION
     SELECT receipt.badguy, receipt.rdate,notes, amount
     FROM <...>
)
Charles