Pages

Thursday, November 17, 2011

Useful PDI steps' commands

Wild card expression
File Names Starts with 100047 and end with  DIS.DAT
${Internal.Job.Filename.Directory}  100047*DIS.DAT <

File names end up with xls extension
${Internal.Transformation.Filename.Directory}\matchdata    .*\.xls


Java scripts
Replace white spaces, concatenate strings and print fields with line breaks 
var Data_file;
var Date_time;
var header_line;
date_time = Date_time1.replace(" ", "-");
Data_file = '82246_data_extraction_' + Date_time1.replace(" ", "-") + '.xls';
header_line = '========================================== \r\n' + 
               'Date & Time  :' + date_time + '\r\n' + 'Output File   :' + Data_file + '\r\n'

If and replace function usage
var max_imported_last_call_new;
if (max_imported_last_call != null) 
       { max_imported_last_call_new=replace(max_imported_last_call, "/", "-"); }
else { max_imported_last_call_new='2000-01-01 00:00:00.0'; }

If and Data Type Conversion
var new_dispo_file_name;
var wave;
if (str2num(filename_date) == str2num(SERVER_DATE)){
new_dispo_file_name = XXXXXX + filename_date + 'CVAR' + num2str(str2num(wave) + 1) + 'DIS';}
else {
new_dispo_file_name = XXXXXX + SERVER_DATE + 'CVAR' + 0 + 'DIS';}

AND and OR conditions 

var IBM_DISPOSITION_CODE;
var fail_number = 0;
IBM_DISPOSITION_CODE = '000';
if (ADDR == null || CITY == null || ZIPCODE == null) {
IBM_DISPOSITION_CODE = '009';
fail_number++;}

if (x_salutation == null && (
(country=='BE' && language=='Dutch') ||
(country=='BE' && language=='French') ||
(country=='FR' && language=='French') ||
(country=='CH' && language=='Italian')  )) {
IBM_DISPOSITION_CODE = '011';
fail_number++;}


Date type (string to date conversion)
eoweek = str2date(date_val,"dd-MMM-yy");
quarter_no = quarter(eoweek);

var SurveyResults_filename = system_date + "_82430SurveyResults";
var SampleDisposition_filename = system_date + "_CumminsDispositionStatus";

var loaddatetime = system_date.substr(0,12) + "00";
var yesterday = dateAdd(today, "d", -1);
var dayb4yesterday = dateAdd(today, "d", -2);


var c_date = date2str(LAST_CALL,"MM/dd/yyyy") + " " + num2str(LAST_TIME/3600, "00") + ":" + (num2str(LAST_TIME%3600/60, "00")) + ":" + (num2str(LAST_TIME%60, "00")) ;

Regular exression
 if ( substr(timetype,0,4) == 'GMT+' || substr(timetype,0,4) == 'GMT-')
{   var re = /([-+])(\d+)(.?)(3?)/.exec(timetype);
    xmins=re[4]
else{mins='00';}
var x = re[2].length;
if ( x == 1) {hr = '0' + re[2]; }
else {hr = re[2]; }
temptime = re[1] + hr + ':' + mins;
}

.*\.add$ - everything ends with ".add"

Monday, November 14, 2011

PostgreSQL 9.2 Volume 1

PostgreSQL is relational database management system (RDBMS).
Architecture
Use client / server architecture. Server handles multiple concurrent connections from clients. It starts new process called "forks" for each new connection.

Create DB: $ createdb my_database           $ dropdb my_database
                  $ /usr/local/pgsql/bin/ createdb my_database

Access DB $ psql my_database
my_database => SELECT version();

Internal commands
my_database --> \h    - help
my_database --> \q    - quit from plsql to shell
my_database --> \i    - read command from specific file
my_database --> \b    - backspace
my_database --> \f    - form feed
my_database --> \n    - newline
my_database --> \r    - carriage return
my_database --> \t    - tab
my_database --> \o, \oo, \ooo (o = 0 - 7) octal byte value
my_database --> \xh, \xhh (h = 0 - 9, A - F)   hexadecimal byte value
my_database --> \uxxxx, \Uxxxxxxxx (x = 0 - 9, A - F)  16 or 32-bit hexadecimal Unicode character value

Create table
CREATE TABLE films (
    code        char(5) PRIMARY KEY DEFAULT nextval('school_id_seq')
    vector  int[][], -- 2 dimension array,
    name   varchar(40) NOT NULL CHECK (name <> '')
    ddid     integer CHECK (did > 100),
    price numeric DEFAULT 9.99,
    date_prod   date,
    kind        varchar(10),
    len         interval hour to minute,
    modtime   timestamp DEFAULT current_timestamp, -- default value is current time
    CONSTRAINT production UNIQUE(date_prod),
    --CONSTRAINT code_title PRIMARY KEY(code,title)
);
Joining tables 
SELECT * FROM table1 a INNER JOIN table2 b ON (a.name = b.name); 
SELECT * FROM table1 a LEFT OUTER JOIN table2 b ON (a.name = b.name); 
SELECT * FROM table1 a RIGHT OUTER JOIN table2 b ON (a.name = b.name);

3. Advanced Features
Transaction concept (all-or-nothing)
Transactions are a fundamental concept of all database systems. The essential point of a transaction is that it bundles multiple steps into a single, all-or-nothing operation. The intermediate states between the steps are not visible to other concurrent transactions, and if some failure occurs that prevents the transaction from completing, then none of the steps affect the database at all. A transaction is said to be atomic: from the point of view of other transactions, it either happens completely or not at all.

when multiple transactions are running concurrently, each one should not be able to see the incomplete changes made by others. To facilitate these iPostgreSQL, a transaction is set up by surrounding the SQL commands of the transaction with BEGIN and COMMIT commands

If, partway through the transaction, we decide we do not want to commit (perhaps bank balance went negative), we can issue the command ROLLBACK instead of COMMIT, and all our updates so far will be cancelled. if you are sure you won't need to roll back to a particular savepoint again, it can be released, so the system can free some resources. Keep in mind that either releasing or rolling back to a savepoint will automatically release all save-points that were defined after it.
BEGIN;
UPDATE accounts SET balance = balance - 100.00 WHERE name = 'Alice';
SAVEPOINT my_savepoint;
UPDATE accounts SET balance = balance + 100.00 WHERE name = 'Bob';
-- oops ... forget that and use Wally's account
ROLLBACK TO my_savepoint;
UPDATE accounts SET balance = balance + 100.00 
    WHERE name = 'Wally';
COMMIT;
END;
Window function
window function performs a calculation across a set of table rows that are somehow related to the current row. Unlike regular aggregate functions, use of a window function does not cause rows to become grouped into a single output row. Behind the scenes, the window function is able to access more than just the current row of the query result. Not allowed within where clause. 
This shows how to compare each employee's salary with the average salary in his or her department.
SELECT depname, empno, salary, avg(salary) OVER (PARTITION BY depname) FROM empsalary;
SELECT depname, empno, salary, rank() OVER (PARTITION BY depname ORDER BY salary DESC) FROM empsalary;

depname  | empno | salary | rank 
-----------+-------+--------+------
 develop   |     8 |   6000 |    1
 develop   |    10 |   5200 |    2
 develop   |     9 |   4500 |    4
 develop   |     7 |   4200 |    5
 personnel |     2 |   3900 |    1
 personnel |     5 |   3500 |    2
 sales     |     1 |   5000 |    1
 sales     |     4 |   4800 |    2
OVER clause directly following the window function's name and argument(s). The OVERclause determines exactly how the rows of the query are split up for processing by the window function. The PARTITION BY list within OVERspecifies dividing the rows into groups, or partitions, that share the same values of the PARTITION BY expression(s).
When a query involves multiple window functions, it is possible to write out each one with a separate OVER clause, but this is duplicative and error-prone if the same windowing behavior is wanted for several functions. Instead, each windowing behavior can be named in a WINDOW clause and then referenced in OVER. For example:
SELECT sum(salary) OVER w, avg(salary) OVER w
  FROM empsalary
  WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);


Inheritance

Inheritance is a concept from object-oriented databases. 
CREATE TABLE cities ( name text, population real, altitude int );
CREATE TABLE capitals ( state char(2))  INHERITS (cities);
On the other hand, the following query finds all the cities that are not state capitals and are situated at an altitude of 500 feet or higher:
SELECT name, altitude FROM ONLY cities WHERE altitude > 500;

Monday, November 7, 2011

Temporary table inside a PostgreSQL function

1. First, create a TYPE Object defining returning fields.
CREATE TYPE accounts.weekly_payroll_report_type AS(
batch integer,
project varchar,
language varchar,
intcode VARCHAR,
bcode integer,
description VARCHAR,
p_tot_hrs NUMERIC,
pay_amount NUMERIC );
2. Create the function
CREATE OR REPLACE FUNCTION accounts.weekly_payroll_report_indirect(integer)
RETURNS setof accounts.weekly_payroll_report_type
AS $$
DECLARE
int_payrate NUMERIC;
 cur_timecard CURSOR FOR select t.batch , t.language, t.project, t.intcode AS t_intcode,
FROM accounts.timecard_duration_view t
INNER JOIN task k ON (k.bcode = t.bcode  AND  UPPER(k.billable) = UPPER(t.billable))
WHERE t.batch = $1 AND UPPER(k.billable) = 'Y'
GROUP BY 1, 2, 3, 4, 5 ,6
cur_pay CURSOR FOR SELECT batch, project, intcode as p_intcode , sum_hours AS p_tot_hrs FROM accounts.payroll_hours_view p WHERE batch = $1; 
BEGIN
CREATE TEMPORARY TABLE temp_payroll_val(
tmp_batch INTEGER, tmp_project VARCHAR,
tmp_p_tot_hrs NUMERIC, tmp_pay_amount NUMERIC) on commit drop;
FOR rec in cur_pay
LOOP FOR rec1 in cur_timecard LOOP
IF (rec.batch::INT = rec1.batch::INT AND rec.project::TEXT = rec1.project::TEXT AND rec.p_intcode = rec1.t_intcode) THEN
SELECT SUM(sum_duration) INTO sum_duration_per_intcode FROM accounts.timecard_duration_view
WHERE batch = rec1.batch AND project = rec1.project AND intcode =  rec1.t_intcode ; SELECT r.amount INTO int_payrate FROM accounts.payroll pp  INNER JOIN accounts.ratecode r ON (UPPER(pp.pay_rate) = UPPER(r.pay_rate))
INSERT INTO temp_payroll_val VALUES (rec.batch, rec.project, rec1.language, rec1.t_intcode, rec1.t_bcode, rec1.description, ROUND(prorated_hrs, 2), (int_payrate * ROUND(prorated_hrs, 2)));
  ELSE
prorated_hrs = 0;
END IF;
END IF;
END LOOP;
END LOOP;
FOR tem_val IN select * FROM temp_payroll_val
LOOP
RETURN NEXT tem_val;
END LOOP;
  RETURN ;
END;
$$ LANGUAGE plpgsql VOLATILE
2. Read the data from function         select * from accounts.weekly_payroll_report_indirect(201129);

Sunday, October 30, 2011

Return query from PostgreSQL function

  1. Create a user defined type or a dummy table object. Fields and data type of the fields need to be same as the returning fields value of the function.
CREATE type production_int_time_figures_func_type AS(
project varchar,
language varchar,
daily_duration_sec numeric,
week_duration_sec numeric,
tot_duration_sec numeric
);
     2. Create the function
(Function to get interviewed time in seconds by giving start and end dates as parameters0

CREATE OR REPLACE FUNCTION production_int_time_figures_func(run_date date, from_date date)
  RETURNS SETOF production_int_time_figures_func_type AS
$BODY$
DECLARE
r production_int_time_figures_func_type%rowtype;
BEGIN
FOR r IN 
SELECT timecard.project, UPPER(trim(timecard.language)) ,
sum(CASE
            WHEN (date(Run_Date) - date(timecard.end_date)) <= 1 AND (date(timecard.end_date) > date(From_date)) THEN timecard.duration
            ELSE 0::numeric END) AS daily_duration_sec,
sum(CASE
            WHEN (date(Run_Date) - date(timecard.end_date)) <= 7 AND (date(timecard.end_date) > date(From_date)) THEN timecard.duration
            ELSE 0::numeric END) AS week_duration_sec,
sum(CASE WHEN (date(timecard.end_date) > date(From_date)) THEN timecard.duration ELSE 0::numeric END) AS tot_duration_sec
FROM accounts.timecard
WHERE (timecard.bcode::integer IN
(SELECT production_tasks_lookup.bcode FROM production_tasks_lookup
WHERE production_tasks_lookup.task_type::text = UPPER(TRIM('INT'::text))))
AND (timecard.project::text IN ( SELECT prodrep.project::character varying AS project
FROM accounts.prodrep))
GROUP BY timecard.project, UPPER(trim(timecard.language))
ORDER BY timecard.project, UPPER(trim(timecard.language))
LOOP 
RETURN NEXT r;
END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE


CREATE OR REPLACE FUNCTION production_int_time_figures_func(run_date date, from_date date)
  RETURNS SETOF production_int_time_figures_func_type AS
$BODY$
DECLARE
r production_int_time_figures_func_type%rowtype;
BEGIN
FOR r IN 
SELECT ....... FROM ..........
LOOP 
RETURN NEXT r;
END LOOP;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE

    3. Retrieve data from function
select * FROM production_int_time_figures_func('2011-10-12', '2009-09-12');

Monday, October 24, 2011

Pass parameters from main report to table's data source in iReport

Following steps help to pass parameters from main report to table data source in iReport (3.6.7 or 4.1.2)
  1. Create required parameters in the main report
    • right clicking on the parameters section of main report
    • add parameter
    • set the properties (data type)
    • set default expression (optional)
  1. Create parameters within the sub data source
    • Set name , data type as same as main report parameters
  1. Map the parameters in main report and data set
    • Right click on the table and click on Edit Table Dataset
    • Select the parameters
    • Click on add
    • Choose the parameter (created in dataset) from upper combo
    • Assign value expression (parameter which added in step 1)

Saturday, October 22, 2011

jasper variable expressions + ireport

Divide by zero error
use of following command in expression allows to eliminate decide by zero error in jasper. $F{feild_name1} and $F{feild_name2} are fields value return from query. if the denominator ($F{feild_name1}) is equal to 0 then command returns 0. Else this returns $F{feild_name2}.doubleValue() / $F{feild_name1}.doubleValue().
new Double(($F{feild_name1}.doubleValue() == 0.00) ? 0.00 : ($F{feild_name2}.doubleValue() / $F{feild_name1}.doubleValue() * 100))
new Double(($F{wave}.toString() == null) ? $F{project} : ($F{project}.toString() + $F{wave}.toString()))

Java servlet use in expression area.
Utils() is the Java class name. com.mycompany.utils is Java package name. filed value is used in Java servlet as a string value and return the output value.
(new com.mycompany.utils.Utils()).hourFormat($F{feild_name2}.toString())
Return current date
use of following  phase in parameter expression area will set set current date as default parameter value.
new java.util.Date()

Return exact date
use of following  phase in parameter expression area will set set "2000- 1- 1" as default parameter value.
new java.util.Date(new GregorianCalendar(2000, 1, 1).getTime().getTime())
If, Elsif and Else condition in Jasper 



new String(($F{project_type}.toString() == "I") ? "IT" :
    (new String(($F{project_type}.toString() == "M") ? "Medical" :
        ((new String(($F{project_type}.toString() == "C") ? "Consumer" :
            ((new String(($F{project_type}.toString() == "X") ? "Other/Dont know" :
            ("- ") )))
                )))
           )
     )
)

Wednesday, October 19, 2011

Read Java servlet in ireport + convert seconds value to hh-mm-ss format

1.Create a java file        

        $ vim utils.java

package ronin.java.servlets;
public class sec_convert
{
        public static String hourFormat(String[] args)
        {
                int duration = Integer.parseInt(args[0]);
                int seconds = duration % 60;
                int minutes = ( duration % 3600 ) / 60 ;
                int hours = duration / 3600 ;


                StringBuffer buffer = new StringBuffer( 10 );


                buffer.append( hours < 10 ? "0" + hours : hours );
                buffer.append( ":" );
                buffer.append( minutes < 10 ? "0" + minutes : minutes );
                buffer.append( ":" );
                buffer.append( seconds < 10 ? "0" + seconds : seconds );


                return( buffer.toString() );
//              System.out.println(buffer.toString() );
        } 
}

Navigate to folder where source file is

2. Compile the class using following command
               $  javac -d . utils.java
this creates "ronin/java/servlets" folder structure

3.To make the jar file
               $ JAR CF jar_file_name.jar class_name.class
               $ jar cf utils.jar utils.class

4. Use following command in Ireport variable expression area

(new ronin.java.servlets.utils()).hourFormat($F{tot_duration_sec}.toString())


return values of $F{tot_duration_sec} field will be displayed in hh-mm-ss format

Friday, August 26, 2011

Show negative values in different format - Jasper - ireport

This is a sample to show negative values in different colour.


1.First duplicate the variable field by coping and paste cell
2.Write following expression in the "print when expression" area in property window.
              $V{Variances}.doubleValue()<0
3.Change the forecolor property in property window into Red
4.Change original cell's "print when expression" as follows
              $V{Variances}.doubleValue()>0
5. Position both original and duplicated cell in same position.
6. save and run the report. It will print the negative values in red colour and positive values in black colour as we defined in "Print when expression"

Tuesday, March 29, 2011

Predefined PL/SQL Exceptions

ExceptionRaised when ...
ACCESS_INTO_NULLA program attempts to assign values to the attributes of an uninitialized object.
CASE_NOT_FOUNDNone of the choices in the WHEN clauses of a CASE statement is selected, and there is no ELSE clause.
COLLECTION_IS_NULLA program attempts to apply collection methods other than EXISTS to an uninitialized nested table or varray, or the program attempts to assign values to the elements of an uninitialized nested table or varray.
CURSOR_ALREADY_OPENA program attempts to open an already open cursor. A cursor must be closed before it can be reopened. A cursor FOR loop automatically opens the cursor to which it refers, so your program cannot open that cursor inside the loop.
DUP_VAL_ON_INDEXA program attempts to store duplicate values in a database column that is constrained by a unique index.
INVALID_CURSORA program attempts a cursor operation that is not allowed, such as closing an unopened cursor.
INVALID_NUMBERIn a SQL statement, the conversion of a character string into a number fails because the string does not represent a valid number. (In procedural statements, VALUE_ERROR is raised.) This exception is also raised when the LIMIT-clause expression in a bulk FETCH statement does not evaluate to a positive number.
LOGIN_DENIEDA program attempts to log on to Oracle with an invalid username or password.
NO_DATA_FOUNDSELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index-by table.Because this exception is used internally by some SQL functions to signal that they are finished, you should not rely on this exception being propagated if you raise it within a function that is called as part of a query.
NOT_LOGGED_ONA program issues a database call without being connected to Oracle.
PROGRAM_ERRORPL/SQL has an internal problem.
ROWTYPE_MISMATCHThe host cursor variable and PL/SQL cursor variable involved in an assignment have incompatible return types. For example, when an open host cursor variable is passed to a stored subprogram, the return types of the actual and formal parameters must be compatible.
SELF_IS_NULLA program attempts to call a MEMBER method, but the instance of the object type has not been initialized. The built-in parameter SELF points to the object, and is always the first parameter passed to a MEMBERmethod.
STORAGE_ERRORPL/SQL runs out of memory or memory has been corrupted.
SUBSCRIPT_BEYOND_COUNTA program references a nested table or varray element using an index number larger than the number of elements in the collection.
SUBSCRIPT_OUTSIDE_LIMITA program references a nested table or varray element using an index number (-1 for example) that is outside the legal range.
SYS_INVALID_ROWIDThe conversion of a character string into a universal rowid fails because the character string does not represent a valid rowid.
TIMEOUT_ON_RESOURCEA time-out occurs while Oracle is waiting for a resource.
TOO_MANY_ROWSSELECT INTO statement returns more than one row.
VALUE_ERRORAn arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural statements,VALUE_ERROR is raised if the conversion of a character string into a number fails. (In SQL statements,INVALID_NUMBER is raised.)
ZERO_DIVIDEA program attempts to divide a number by zero.

Wednesday, March 23, 2011

ORACLE PLSQL - Report Formatting

Changing a Column Heading

COLUMN LAST_NAME        HEADING 'LAST NAME'
COLUMN SALARY           HEADING 'MONTHLY SALARY'
COLUMN COMMISSION_PCT   HEADING COMMISSION
SELECT LAST_NAME, SALARY, COMMISSION_PCT  FROM EMP_DETAILS_VIEW
WHERE JOB_ID='SA_MAN';
LAST NAME                 MONTHLY SALARY COMMISSION
------------------------- -------------- ----------
Russell                            14000         .4
Partners                           13500         .3

Splitting a Column Heading
COLUMN SALARY HEADING 'MONTHLY|SALARY'
COLUMN LAST_NAME HEADING 'LAST|NAME'


LAST                         MONTHLY
NAME                          SALARY COMMISSION
------------------------- ---------- ----------
Russell                        14000         .4
Partners                       13500         .3
Setting the Underline Character
SET UNDERLINE =
/
LAST                         MONTHLY
NAME                          SALARY COMMISSION
========================= ========== ==========
Russell                        14000         .4
Partners                       13500         .3

Formatting a NUMBER Column
COLUMN SALARY FORMAT $99,990
LAST                       MONTHLY
NAME                        SALARY COMMISSION
------------------------- -------- ----------
Russell                    $14,000         .4
Partners                   $13,500         .3

Formatting a Character Column
LAST  MONTHLY
NAME   SALARY COMMISSION
---- -------- ----------
Russ  $14,000         .4
ell


Resetting Column Display Attributes to their Defaults
CLEAR COLUMNS

Suppressing Duplicate Values in a Break Column
BREAK ON DEPARTMENT_ID;

BREAK ON DEPARTMENT_ID SKIP 1

SELECT DEPARTMENT_ID, LAST_NAME, SALARY  
FROM EMP_DETAILS_VIEW
WHERE SALARY > 12000 
ORDER BY DEPARTMENT_ID;

DEPARTMENT_ID LAST_NAME                     SALARY
------------- ------------------------- ----------
           20 Hartstein                      13000

           80 Russell                        14000
              Partners                       13500

           90 King                           24000
              Kochhar                        17000

Combining Spacing Techniques
BREAK ON DEPARTMENT_ID SKIP PAGE ON JOB_ID SKIP 1
TTITLE COL 35 FORMAT 9 'Page:' SQL.PNO




Page: 1
DEPARTMENT_ID JOB_ID     LAST_NAME                     SALARY
------------- ---------- ------------------------- ----------
           20 MK_MAN     Hartstein                      13000

Page: 2
DEPARTMENT_ID JOB_ID     LAST_NAME                     SALARY
------------- ---------- ------------------------- ----------
           80 SA_MAN     Russell                        14000
                         Partners                       13500

Computing and Printing Subtotals
break on DEPARTMENT_ID page  nodup on JOB_ID skip 1 nodup
COMPUTE SUM OF SALARY ON DEPARTMENT_ID

DEPARTMENT_ID JOB_ID     LAST_NAME                     SALARY
------------- ---------- ------------------------- ----------
           20 MK_MAN     Hartstein                      13000
************* **********                           ----------
sum                                                     13000

DEPARTMENT_ID JOB_ID     LAST_NAME                     SALARY
------------- ---------- ------------------------- ----------
           80 SA_MAN     Russell                        14000
                         Partners                       13500

************* **********                           ----------
sum                                                     27500
Example
COLUMN DUMMY NOPRINT;
COMPUTE SUM OF SALARY ON DUMMY;
BREAK ON DUMMY SKIP 1;
SELECT DEPARTMENT_ID DUMMY,DEPARTMENT_ID, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW WHERE SALARY>12000 ORDER BY DEPARTMENT_ID;
DEPARTMENT_ID LAST_NAME                     SALARY
------------- ------------------------- ----------
           20 Hartstein                      13000
                                        ----------
                                             13000

           80 Russell                        14000
           80 Partners                       13500
                                        ----------
                                             27500

           90 King                           24000
           90 Kochhar                        17000
           90 De Haan                        17000
                                        ----------
                                             58000
Computing Multiple Summary Lines on the Same Break Column
BREAK ON DEPARTMENT_ID
COMPUTE AVG SUM OF SALARY ON DEPARTMENT_ID
SELECT DEPARTMENT_ID, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW WHERE DEPARTMENT_ID = 30
ORDER BY DEPARTMENT_ID, SALARY;
DEPARTMENT_ID LAST_NAME                     SALARY
------------- ------------------------- ----------
           30 Colmenares                      2500
              Himuro                          2600
              Tobias                          2800
              Baida                           2900
              Khoo                            3100
              Raphaely                       11000
*************                           ----------
avg                                           4150
sum                                          24900
Listing and Removing COMPUTE Definitions
CLEAR BREAKS
CLEAR COMPUTES
Setting the Top and Bottom Titles and Headers and Footers
TTITLE ON
BTITLE ON
TTITLE CENTER - "ACME SALES DEPARTMENT PERSONNEL REPORT"
BTITLE CENTER "COMPANY CONFIDENTIAL"
REPHEADER PAGE CENTER 'PERFECT WIDGETS'
RIGHT 'SALES DEPARTMENT' SKIP 2
SET LINESIZE 60

ACME SALES DEPARTMENT PERSONNEL REPORT
                            PERFECT WIDGETS

                         COMPANY CONFIDENTIAL

                ACME SALES DEPARTMENT PERSONNEL REPORT
DEPARTMENT_ID LAST_NAME                     SALARY
------------- ------------------------- ----------
           30 Colmenares                      2500
           30 Himuro                          2600
           30 Tobias                          2800
           30 Baida                           2900
           30 Khoo                            3100
           30 Raphaely                       11000

                         COMPANY CONFIDENTIAL

Setting Page Dimensions

To set the number of lines between the beginning of each page and the top title, use the NEWPAGE variable of the SET command:
SET NEWPAGE number_of_lines
To set the number of lines on a page, use the PAGESIZE variable of the SET command:
SET PAGESIZE number_of_lines
You can change the line width using the LINESIZE variable of the SET command:
SET LINESIZE number_of_characters

SET PAGESIZE 66
SET NEWPAGE 0
SET LINESIZE 70

Creating a Flat File
SET NEWPAGE 0
SET SPACE 0
SET LINESIZE 80
SET PAGESIZE 0
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET MARKUP HTML OFF SPOOL OFF
To store the results of a query in a file—and still display them on the screen—enter the SPOOL command in the following form:

SPOOL file_name

Sending Query Results to a Printer First, use EDIT to create the script with your operating system text editor.
EDIT EMPRPT
Next, enter the following commands into the file, using your text editor:
SPOOL TEMP
CLEAR COLUMNS
CLEAR BREAKS
CLEAR COMPUTES

COLUMN DEPARTMENT_ID HEADING DEPARTMENT
COLUMN LAST_NAME HEADING 'LAST NAME'
COLUMN SALARY HEADING 'MONTHLY SALARY' FORMAT $99,999

BREAK ON DEPARTMENT_ID SKIP 1 ON REPORT
COMPUTE SUM OF SALARY ON DEPARTMENT_ID
COMPUTE SUM OF SALARY ON REPORT

SET PAGESIZE 24
SET NEWPAGE 0
SET LINESIZE 70

TTITLE CENTER 'A C M E  W I D G E T' SKIP 2 -
LEFT 'EMPLOYEE REPORT' RIGHT 'PAGE:' -
FORMAT 999 SQL.PNO SKIP 2
BTITLE CENTER 'COMPANY CONFIDENTIAL'

SELECT DEPARTMENT_ID, LAST_NAME, SALARY
FROM EMP_DETAILS_VIEW
WHERE SALARY>12000
ORDER BY DEPARTMENT_ID;

SPOOL OFF
If you do not want to see the output on your screen, you can also add SET TERMOUT OFF to the beginning of the file and SET TERMOUT ON to the end of the file. run the script EMPRPT:
@EMPRPT
SQL*Plus displays the output on your screen (unless you set TERMOUT to OFF), and spools it to the file TEMP:
A C M E  W I D G E T

EMPLOYEE REPORT                                              PAGE: 1

DEPARTMENT LAST NAME                 MONTHLY SALARY
---------- ------------------------- --------------
        20 Hartstein                        $13,000
**********                           --------------
sum                                         $13,000

        80 Russell                          $14,000
           Partners                         $13,500
**********                           --------------
sum                                         $27,500

        90 King                             $24,000
           Kochhar                          $17,000
           De Haan                          $17,000
**********                           --------------
sum                                         $58,000

                                     --------------
sum                                         $98,500
                         COMPANY CONFIDENTIAL
Ref: http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b12170/ch7.htm