Saturday, July 07, 2012

Like No Other

APEX pie charts allow you to limit the number of records that are displayed in the chart. This can be controlled by editing the Series and setting the Maximum Rows parameter. However, APEX will automatically add an "Other" slice to your chart, which represents all of the other data from the query. Consider this example: you have 10 different widget types, and 10 of each type for a total of 100 units. Here's some SQL to quickly create this scenario, if you want to follow along:
CREATE TABLE widgets (widget_type VARCHAR2(10))
/

DECLARE
  z NUMBER := 1;
BEGIN
FOR y IN 1..10
LOOP
  FOR x IN 1..10
  LOOP
    INSERT INTO widgets VALUES ('Type ' || z);
    z := z + 1;
  END LOOP;
  z := 1;
END LOOP;
END;
/
If you wanted to sum them based on type and just see the first five types, you can use a simple SQL statement like this:
SELECT 
  NULL link,
  widget_type label, 
  COUNT(*) value
FROM 
  widgets
GROUP BY 
  widget_type 
ORDER BY 2
Which will in turn, produce a chart that looks like this: SafariScreenSnapz001 Clearly, not what you may expected, as you only wanted to see the top 5 widgets, not the top 5 plus all additional records grouped into an "other" slice. Visually, this may be misleading to the user. To get just the top 5 records, we have to use an inline SQL statement that will select from our original SQL statement and limit the results to just 5 records:
SELECT
  link,
  label,
  value
FROM
  (
  SELECT 
    NULL link,
    widget_type label, 
    COUNT(*) value
  FROM 
    widgets
  GROUP BY 
    widget_type 
  ORDER BY 2
  )
WHERE
  rownum < 6
With this approach, we let APEX create the chart and append the Other slice to the results. We then siphon off just the first five records, which in this case, will not include the Other slice. The result is something closer to what many users would expect: SafariScreenSnapz002 Using this approach, the value of the Maximum Rows can be set anything greater than or equal to the value compared to ROWNUM in the last line of the second SQL statement, as we will be using the WHERE clause to limit how many records are displayed.

2 comments:

jts194 said...

Scott,
We're using APEX 4.1 and APEX Listener 1.1.3. Have you ever had a problem with stored procedures parameter/signature caching. For example, if I create a stored procedure with two parameters (default null), I can access via browser through /apex/schema_name.procedure_name?p_one=1&p_tw0=2. Now, if I had a third parameter and change my URL signature to p_one=1&p_tw0=2&p_three=3, p_three is always null. Whenever the procedure is created or accessed, it seems its caching the signature and not acknowledging the new parameters. Any insight would be appreciated. Thanks
Josh S.

Scott said...

Josh,

Not sure how this comment relates to this post.

- Scott -