If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > MySQL > subtract fields in the same table

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 01-22-09, 01:18
homer.favenir homer.favenir is offline
Registered User
 
Join Date: Oct 2007
Location: Manila, Philippines
Posts: 132
subtract fields in the same table

hi everyone,
i just cant figure out how to subtract fields in the same table.
Code:
SELECT
SUM( a.amountfigure ) AS 'Dollars'
, 'Buying' AS 'Transact'
FROM forex_tbl a
WHERE a.currency = 'USD' AND a.transactiontype = 'Buying'

UNION ALL

SELECT
SUM( b.amountfigure ) AS 'Dollars'
, 'Selling' AS 'Transact'
FROM forex_tbl b
WHERE b.currency = 'USD' AND b.transactiontype = 'Selling';
i want the 'Dollars' in buying be subtract to 'Dollars' in selling.
how can i do this.

thanks

ok i already get it...
Code:
SELECT
(SELECT
SUM( a.amountfigure ) AS 'Dollars'
FROM forex_tbl a
WHERE a.currency = 'USD' AND a.transactiontype = 'Buying') AS 'Buying'

,(SELECT
SUM( b.amountfigure ) AS 'Dollars'
FROM forex_tbl b
WHERE b.currency = 'USD' AND b.transactiontype = 'Selling') AS 'Selling';
whew....
any other solutions guys?

thanks
__________________
Take Nothing But Pictures;
Leave Nothing But Footprints;
Kill Nothing But Time;

Last edited by homer.favenir; 01-22-09 at 01:22.
Reply With Quote
  #2 (permalink)  
Old 01-22-09, 03:25
gvee gvee is offline
www.gvee.co.uk
 
Join Date: Jan 2007
Location: UK
Posts: 10,156
This any good?
Code:
SELECT Sum(CASE WHEN transactiontype = 'Buying'  THEN amountfigure END) As [Buying]
     , Sum(CASE WHEN transactiontype = 'Selling' THEN amountfigure END) As [Selling]
FROM   forex_tbl
WHERE  currency = 'USD'

SELECT Sum(CASE WHEN transactiontype = 'Buying'  THEN amountfigure END)
     - Sum(CASE WHEN transactiontype = 'Selling' THEN amountfigure END) As [Dollars]
FROM   forex_tbl
WHERE  currency = 'USD'
__________________
George
Twitter | Blog
Reply With Quote
Reply

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On