显示标签为“examples”的博文。显示所有博文
显示标签为“examples”的博文。显示所有博文

2014年8月19日星期二

Examples of esProc as used in set Operation

Set operations are frequently used in statistical analysis with structured data, For example, listing all students who has published papers; listing all staff who has participated in all previous training; selecting qualified students in examination for re-examand so on. Within exProc, application of set is everywhere. The most commonly used sequence and sequence table data types are all sets. Therefore, better understanding and using of set helps to complete data computation in a more reasonable and faster way. 

For example, the table below contains some sales data:

Now we need to select customers who entered Top 20 revenue contributors (Top 20 customers) in every month of 2013. To solve this problem we can first select all sales data for 2013, group them and to get the statistics for each month. Then we can do a loop to select the Top 20 customers for each month. The intersection of the Top 20 lists for all 12 months will contain the name of customers we wanted. Such complex problems are too difficult to be handled by SQL or stored procedures.
With esProc, we can split complex problems into different steps, and do the computations step by step to get the final result. First, from the sales data we can retieve those for 2013, and group them by month: 

esProc’s grouping of data is real grouping, which actually separates data into different groups according to the criterion. This is different from SQL, in which the“group by” command can only return the aggregated result of a grouping. After grouping, the data in A3 is as following: 
Before grouping, all data will be sorted automatically. Each group is a set of sales records. For example, the data for March is as following: 
To know the total sales revenue for each customer in every month, we need to further split the data by customers. In esProc, we only need to do loop on data for each month, and group them by customers respectively. We can use A.(x) to to do loop on set members, without the need to code for loop.  
After further grouping, the monthly data in A4 is a set of sets: 
Now, the data for March is as following: 
We can see that each group in data for March is the transaction data for certain customer. 

The set used in esProc is different from that in mathematical concepts. They are ordered sets and therefore can meet the statistical needs of sorting and selection by position, etc. Then we can find the Top 20 customers for each month: 
In A5, do loop on the data for each month to get the Top 20 customers for each month. And in A6, listthe names and monthly revenues of these customers. The computation result in A6 is as following: 
Finally, we can further solve the problem: 
Generate the name lists of Top 20 customers in A7 for each month. And finally in A8 we can find the intersection of the Top 20 lists for each month as following: 
From this example we can find that ordered sets in esProc can make problem solving more intuitive. Within the set, we can easily do grouping, sorting and other computations. This helps to make the goal for each step of data processing clear and easy to understand. Meanwhile, the using of set concept can reduce the complexity and coding workload for loops on set members and set operations, such as the computation for set intersection. 

2014年8月7日星期四

Code Examples of Processing json Data with esProc

esProc can process json data. Here we'll introduce some of the applications through examples. 1. Analyzing and generating json data with esProc; 2. Data-interchange between esProc and application program through json; 3.Reading json file data in esProc.

A Analyzing and generating json data with esProc
Generally speaking, json is a format used by webpage js program and Java's server-side program (such as servlet)to interchange data. While data access between Java's server-side program and the databases adopts SQL result set format. esProc can act as an intermediary in the data computation and data-interchange between the two formats.
In this example, we use esProc to query detailed information of a group of designated employees. Both data input and output will adopt json format. Table employee of database demo contains all information of the employees:
esProc receives an EID list of json format and returns corresponding detailed information of employees in json format. The code is as follows:

1.esProc program test.dfx receives a parameter: jsonEID.
2.esProc completes json analysis, data processing and generates results in json format:
A1Connect to database demo.
A2Retrieve data from table employee.
A3Use import@j function to parse the inputting jsonEID parameter (EID list in json format) and generate a table sequence containing only one field EID.
A4Use align function to get from users data the employee information designated by A3.
A5Convert employee information into json strings. 
A6Return employee information of json format.

B.Interchanging json data between esProc and Java application
In the above example, esProc program is saved as test.dfx file to be called by Java application. Steps for calling the file are as follows:
1.Deploy esProc in Java application.
See esProc Tutorial for detail.

2.Call test.dfx in Java application.
Code example is as follows:
public void testDataServer(){
       Connection con = null;
       com.esproc.jdbc.InternalCStatementst;
           try{
               //Usersid list in json format can be transmitted from browser-side to the program and converted into strings for use. Here process of receiving json data is omitted and value is assigned directly
               String jsonEid="[{EID:8},{EID:32},{EID:44}]";
               //Create a connection
               Class.forName("com.esproc.jdbc.InternalDriver");
               con= DriverManager.getConnection("jdbc:esproc:local://");
               //Call stored procedure. test is the file name of dfx
               st =(com.esproc.jdbc.InternalCStatement)con.prepareCall("call test(?)");
               //Set parameters
               st.setObject(1,jsonEid);
               //Execute stored procedure
               st.execute();
               //Get result set
               ResultSet set = st.getResultSet();
               String jsonEmployee=null;
               if (set.next()) jsonEmployee=set.getString(1);
               //After getting detailed user information injson format, convert it into json objects and return them to browser-side. How to use json Employee is omitted here
            }
            catch(Exception e){
               System.out.println(e);
             }
            finally{
               //Close the connection
               if (con!=null) {
                   try {
                        con.close();
                        }
                   catch(Exception e) {
                                System.out.println(e);
                                     }
               }
           }
}

C Reading and processing json file data in esProc
JSON file test.json contains information including class, serial number, names, subjects,scores, etc. Format is as follows:
[
    {
        "class": "Class one",
        "id": 1,
        "name": "Emily",
        "subject": "English",
        "score": 84
    },
    {
        "class": "Class one",
        "id": 1,
        "name": "Emily",
        "subject": "Math",
        "score": 77
    },

    ......

    {
        "class": "Class one",
        "id": 7,
        "name": "Nicholas",
        "subject": "PE",
        "score": 60
    }
]


It is convenient for esProc to perform the reading and computation of JSON data. After that the result is submitted to Java application in the format of JDBC result set. Steps are as follows:

1. Developing esProc script Use esProc editor to develop script (fromJSON.dfx), read the jsonfile, analyze it and complete the computation:
A1Use read() to read json file in string format;
A2Use import@j()function to parse the json file into a table sequence;
A3Group students ID and summarize the total scores in A4;
A5Sort by total scores in descending order and return result set through result in A7

2. Java application callsfromJSON.dfx to present result.
Steps are omitted here for they are almost the same as those in the above example.

2014年7月31日星期四

Examples of Database Transaction Management with esProc

esProc can write to databases and manage database transactions. Here we'll look at the programming method of rollbacks and controlling transaction submission, etc.
A.Submit transactions automatically
esProc can conveniently execute operations like insert, delete and update. The simplest code is:



In the above figure, insert, update and delete are respectively executed from A2 to A4. Execution of each SQL statement will be submitted automatically. Note that:
1. That three SQL statements are submitted three times is too frequent operations for a database.
2. There exists no transaction relation between the three SQL statements. So, if the execution of one SQL statement fails, the previous SQL statement will remain unaffected.
The following examples are to introduce how to submit transactions in batches and how to compose a transaction with multiple SQL statements in a table sequence.

B.Submit transactions in batches
Import students’ information from students.txt to update table students1 in the database. Since there are a lot of records to be modified, using method of submitting transactions in batches is more reasonable.
 
A1:Define a file object in which students’ information is stored.
A2:Import file content.
A3:Use students' information in A2 to update table students1 in batches. Submitting SQL in batches can avoid accessing the database too frequently. Meanwhile, this can ensure consistency of the data for the submission could succeed or fail simultaneously.

C.Program control transactions
Now we’ll add a new student. The student’s id should be modified to 9 after data are inserted. In order to ensure consistency of the data, submission must be executed after the insertion and modification are proved to be successful. Otherwise rollback should be executed.
 
A1:Connect to the database. Note that connect function uses option @e and the subsequent code will return error message when something wrong happens. If the option is not used, the database will terminate esProc program directly when errors occur.
A2:Execute the insert SQL statement. Note that execute function uses option @k, meaning the transaction will not automatically submitted after it is executed. If the option is not used, the insert SQL statement will be submitted immediately.
A3:Get the result of last operation in the database, i.e., the insert statement. If err variable is zero, the execution is successful; otherwise, err is the error code.
A4:Judging whether err variable, the execution result, is zero. If the answer is yes, the last operation of the insert statement is successful and modification in B4 can be executed.
C4:Get execution result of the update SQL.
A5:Make judgment over err variable. If it is zero, submit the database; otherwise execute rollback.
A6:Close database connection.

2014年7月30日星期三

Example & Comments for SQL Computation Disadvantage (II)

l  Set-lization is not complete.
It is beyond any doubt that set is the basis of mass data computation. Although SQL has the concept of set, it is limited to describing simple result set, and it does not take the set as a basic data type to enlarge its application scope.

Task5  Employees in the company whose birthday are the same as those of others
1
select * from employee
2
where to_char (birthday, ‘MMDD’) in
3
( select to_char(birthday, ‘MMDD’) from employee
4
group by to_char(birthday, ‘MMDD’)
5
having count(*)>1 )

The original intention of grouping is to split the source set into several subsets, and its returned values are also these sub-sets. But SQL cannot describe this kind of "set consisting of sets", so it forcibly conducts the next step aggregating computation on these sub-sets and forms conventional result set.
But sometimes what we want is not the summary value on sub-sets, but rather the subsets themselves. At this time, it is necessary to use from the source set the condition obtained from grouping to query again, so sub-query appears again unavoidably.

Task6 Find out students whose scores ranks in top 10 for all subjects
1
select name
2
from (select name
3
from (select name,
4
rank() over(partition by subject order by score DESC) ranking
5
from score)
6
where ranking<=10)
7
group by name
8
having count(*)=(select count(distinct subject) from score)

Use set-lized train of thought, order and filter the sub-sets of subjects after grouping to select the top 10 of every subject, and then it is possible to complete the task by finding out the intersection set of these sub-sets. But SQL cannot describe the "set of set" and has not the intersection operation to cope with indefinite quantity set. At this time, it is necessary to change the train of thought and use the window function to find out the top 10 of every subject, and then find out, according to student sub-group, the students whose number of appearances is the same as the quantity of subjects, which causes difficulty in understanding.

l  It lacks object reference.
In SQL, the reference relation between tables depends on equivalent foreign key for maintenance and it is impossible to directly use the record at which the foreign key point as the field of this record. In query, it is necessary to seek help of multi-table join or sub-query to complete the query, which causes not only trouble in writing but also low efficiency in operations.

Task7  Female manager’s male employees
Use multi-table join.
1
select A.*
2
from employee A, department B, employee C
3
where A. department=B. department and B. manager=C. name and
4
A.sex ='male' AND C. gender ='female'
Use sub-query.
1
select * from employee
2
where department in
3
(select department from department
4
 where manager in
5
(select name from employee where gender ='female'))

If the department field in the employee table points at the record in the department table while the manager field in the department table points at the record in the employee table, then it is only necessary to write this query condition simply as this kind of intuitive high-efficiency form:
where department.manager.sex ='female' and sex ='male'
But in SQL, it is only possible to use multi-table join or sub-query to write out the two kinds of obviously obscure statements.

Task8  Companies with which employees have their first jobs
Use multi-table join.
1
select name, company, first_company
2
from (select employee.name name, resume.company  company,
3
row_number() over(partition by resume. name
4
order by resume.start_date) work_seq
5
from employee, resume where employee.name = resume.name)
6
where work_seq=1
Use sub-query.
1
select name,
2
(select  company from resume
3
where name=A. name and
4
start date=(select min(start_date) from resume
5
where name=A. name)) first_company
6
from employee A

Without object reference mechanism and the completely set-lized of SQL, it is naturally impossible to handle the sub-table as an attribute of the primary table (field value). Regarding the query of sub-table, there are two methods. The first is to use multi-table join, increase the complexity of the statement, and use filter or grouping to convert the result set into the situation having one-to-one correspondence with the primary table record (the joined record has one-to-one correspondence with the sub-table). The second is to adopt sub-query, and each time compute temporarily the sub-table relating to the primary table record to record sub-sets, and increase the overall computation workload (it is impossible to use with sub-statement in sub-query) and trouble in writing.


Example & Comments for SQL Computation Disadvantage (I)

The computing power of SQL for mass structured data is complete, that is to say, it is impossible to find anything that SQL cannot compute. But its support layer is too low, which can lead to over-elaborate operation in practical application.
The over-elaborate operation is specifically reflected in the following four aspects:
l  Computation without sub-step: SQL requires computation to be written out in one statement, and it is necessary to adopt storage procedure to implement computation step by step. No sub-step not only causes difficulty in thinking, but also makes it difficult to use intermediate result.
l  Set is unordered: SQL does not directly provide the mechanism of using position to refer to set members, and conversion is needed to implement computation relating to order and positioning.
l  Set-lization is not complete: SQL set function is simple and is only used to indicate the query result set and cannot be explicitly applied as basic data type.
l  It lacks object reference: SQL does not support record reference, the association between data tables adopts equivalent foreign key scheme, and in conducting multi-table joint computation, it is necessary to conduct join operation. So it is not only difficult to understand, but also low in efficiency.

Implementing data computation process based on a type of computation system is in fact the process of translating business problem into formalized computation syntax (which is similar to the case in which a primary-school student solves an application problem by translating the problem into formalized four arithmetic operations). Because of the above-mentioned four problems of SQL, in handling complex computation, its model system is inconsistent with people’s natural thinking habit. It causes a great barrier in translating problems, leading to the case that the difficulty to formalize the problem-solving method into computation syntax is much greater than to find the solution of the problem.

We give the following examples to describe respectively the problems in the four aspects.
To make the statement in the examples as simple as possible, here a large number of SQL2003 standard window functions are used. So we adopt the ORACLE database syntax that does a relatively good job in supporting SQL2003 standard as it will be generally more complex to adopt the syntax of other databases to program these SQLs.

l  Computation without sub-step
Carrying out complex computation step by step can reduce the difficulty of the problem to a great extent, conversely, collecting a multi-step computation into one to be completed in just one step increases the complexity of the problem.

Task1 The number of persons of the sales department, where, the number of persons whose native place is NY, and where, the number of female employees?

The number of persons of the sales department
1
select count(*) from employee where department='sales'
Where, the number of persons whose native place is Beijing
1
select count(*) from employee where department=‘sales ’ and native_place='NY'
And where, the number of female employees
1
select count (*) from employee
2
where department='sales' and native_place='NY' and gender ='female'

Conventional thought: Select the persons of the sales department for counting, and from it, find out the persons whose native place is NY for counting, and then further find out the number of female employees for counting. The query each time is based on the existing result last time, so it is not only simple in writing but also higher in efficiency.
But, the computation of SQL cannot be conducted in steps, and it is impossible to reuse the preceding result in answering the next question, and it is only possible to copy the query condition once more.

Task2  Each department selects a pair of male and female employees to form a game team.
1
with A as
2
(select name, department,
3
row_number() over (partition by department order by 1) seq
4
        from employee where gender =‘female’),
5
    B as
6
(select name, department,
7
row_number() over(partition by department order by 1) seq
8
        from employee where sex =‘female’)
9
select name, department from A
10
where department in ( select distinct department from B ) and seq=1
11
union all
12
select name, department from B
13
where department in (select distinct department from A ) and seq=1

Computation without sub-step sometimes not only causes trouble in writing and low efficiency in computation, but even causes serious deformation in the train of thought.

The intuitive thought of this task: For each department cycle, if this department has male and female employees, then select one male employee and one female employee and add them to the result set. But SQL does not support this kind of writing with which the result set is completed step by step (to implement this kind of scheme, it is necessary to use the stored procedure). At this time, it is necessary to change the train of thought into: Select male employee from each department, select female employee from each department, select out, respectively from the two result sets, members whose departments appear in another result set, and finally seek the union of the sets.
Fortunately, there are still with sub-statement and window function over (SQL2003 standard begins to support); otherwise this SQL statement will be simply ugly.

l  The set is unordered.
Ordered computation is very common in mass data computation (obtain the first 3 places/the third place, compare with the preceding period). But SQL adopts the mathematical concept of unordered set, so ordered computation cannot be conducted directly, and it is necessary to adjust the train of thought and change the method.

Task3  Company's employees whose ages are in the middle
1
select name, birthday
2
from (select name, birthday, row_number() over (order by birthday) ranking
3
from employee )
4
where ranking=(select floor((count(*)+1)/2) from employee)

Median is a very common computation, and originally it is only necessary to simple get out, from the ordered set, the members whose positions are in the middle. But SQL unordered set mechanism does not provide the mechanism which directly uses position to access member. It is necessary to create a man-made sequence number field, and then use the condition query method to select it out, causing the case in which a sub-query is needed to complete the query.

Task4  For how many trading days has this stock gone up consecutively in the longest?
1
select max(consecutive_day)
2
from (select count(*) (consecutive_day
3
from (select sum(rise_mark) over(order by trade_date) days_no_gain
4
from (select trade_date,
5
case when
6
closing_price >lag(closing_price) over(order by trade_date)
7
then 0 else 1 end  rise_mark
8
from stock_price) )
9
group by days_no_gain)

Unordered set can also cause train of thought to deform.
The conventional train of thought for computing the number of consecutive days in which the stock rises: Set up a temporary variable whose initial value is 0 to record the consecutive dates in which the stock rises, and then compare it with the preceding day. If the stock does not rise, then clear the variable to 0; if it rises, add 1 to the variable, and see the maximum value appearing from the variable when the cycle is over.

In using SQL, it is impossible to describe this process, so it is necessary to change the train of thought. To compute the accumulate number of days in which stock does not rise from the initial date to the current date, and the one with the same number of days in which stock does not rise is the consecutive trading days in which the stock rises, and from its sub-group, it is possible to find out the interval in which the stock rises, and then seek its maximum count. It is already not so easy to read and understand this statement and it is more difficult to write it out.