home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / database / informix / 1730 < prev    next >
Encoding:
Text File  |  1992-08-15  |  1.9 KB  |  59 lines

  1. Newsgroups: comp.databases.informix
  2. Path: sparky!uunet!zaphod.mps.ohio-state.edu!sgiblab!wetware!cse
  3. From: cse@wetware.com (Scott Ellard)
  4. Subject: Re: conditional select sum() based on field question
  5. Message-ID: <1992Aug15.185641.6075@wetware.com>
  6. Keywords: select sum
  7. Organization: Castle Wetware
  8. References: <297@praeda.UUCP.UUCP>
  9. Date: Sat, 15 Aug 1992 18:56:41 GMT
  10. Lines: 47
  11.  
  12. In article <297@praeda.UUCP.UUCP> pete@praeda.UUCP.UUCP (Pete Frehner) writes:
  13. >
  14. >I have a question regarding selecting a sum from a table of amounts and
  15. >depending upon the type of record, either adding or subtracting the amount
  16. >from the sum.  We are using Informix 4.0 ISQL and R4GL.
  17. >I could do this in two select statements and the difference would be the
  18. >net amount, but this requires that the data be read twice (once for each
  19. >select statment).  
  20.                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  21.  
  22. This implies that the cardinality/selectivity of "order_type" is such
  23. that "order_type" is not indexed.
  24.  
  25. >
  26. >
  27. >   select sum(amount) into total_credits
  28. >       from orders where order_type = "CREDIT"
  29. >
  30. >   select sum(amount) into total_normal_orders 
  31. >       from orders where order_type = "REG"
  32. >
  33. >   let net_amount = total_normal_orders - total_credits 
  34. >
  35. >
  36. >Is there a way that this could be done in one select statment??  Two select
  37. >statments is no big deal for a small database, but this database contains
  38. >hundreds of thousands of orders.  If the data could be read only once it would
  39. >pick up performance quite a bit.
  40.  
  41. Try this:
  42.  
  43.     create table foo
  44.     (
  45.       order_type char(6),
  46.       bar        integer
  47.     );
  48.     insert into foo values("CREDIT", -1);
  49.     insert into foo values("REG",     1);
  50.  
  51.     select sum(O.amount * F.bar)
  52.     from orders O, foo F
  53.     where O.order_type = F.order_type
  54.     and   O.amount is not null;
  55.  
  56. Note: foo could be an existing permanent
  57.     table or it could be created/dropped
  58.     on the fly.
  59.