home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!gatech!darwin.sura.net!dtix!mimsy!nocusuhs!mgr!perez
- From: perez@mgr.hjf.org (Charles Perez)
- Newsgroups: comp.databases.informix
- Subject: Re: conditional select sum() based on field question
- Keywords: select sum
- Message-ID: <1992Aug14.190551.27767@nocusuhs.nnmc.navy.mil>
- Date: 14 Aug 92 19:05:51 GMT
- References: <297@praeda.UUCP.UUCP>
- Sender: news@nocusuhs.nnmc.navy.mil (Netnews Admin Account)
- Organization: HJF AIDS Research Project, Washington DC
- Lines: 63
- Nntp-Posting-Host: 131.158.26.52
-
- In article <297@praeda.UUCP.UUCP> pete@praeda.UUCP.UUCP (Pete Frehner) writes:
- >
- >I have a question regarding selecting a sum from a table of amounts and
- >depending upon the type of record, either adding or subtracting the amount
- >from the sum. We are using Informix 4.0 ISQL and R4GL.
- >
- >I could do this in two select statements and the difference would be the
- >net amount, but this requires that the data be read twice (once for each
- >select statment).
- >
- >
- > select sum(amount) into total_credits
- > from orders where order_type = "CREDIT"
- >
- > select sum(amount) into total_normal_orders
- > from orders where order_type = "REG"
- >
- > let net_amount = total_normal_orders - total_credits
- >
- >
- >Is there a way that this could be done in one select statment?? Two select
- >statments is no big deal for a small database, but this database contains
- >hundreds of thousands of orders. If the data could be read only once it would
- >pick up performance quite a bit.
-
- I would do it this way:
-
- DEFINE
- rorders RECORD
- type LIKE orders.order_type,
- amount LIKE orders.amount
- END RECORD
-
- DECLARE corders CURSOR FOR
- SELECT order_type, sum(amount)
- FROM orders
- WHERE
- (order_type = "CREDIT")
- or (order_type = "REG")
- GROUP BY order_type
-
- FOREACH corders INTO rorders.*
- IF (rorders.order_type = "CREDIT") THEN
- LET total_credits = rorders.amount
- ELSE
- LET total_normal_orders = rorders.amount
- END IF
- END FOREACH
-
- LET net_amount = total_normal_orders - total_credits
-
- This gives you exactly one SQL query to contend with, and the cursor
- shouldn't slow you down. Make sure there is an index primarily on the
- order_type field, or it will still crawl!
-
- Hope this helps.
-
-
- --
- ==========================================================================
- That which is necessary is never evil. If an evil seems necessary, look
- to your context; that's where its root lies. - Charles Perez
- ==========================================================================
-