I have following example of table. Thera can be unlimited branch and customers. I need group this branches and count their customers, then show it's with different columns.
BRANCHNAME CUSTOMERNO
100 1001010
100 1001011
103 1001012
104 1001013
104 1001014
104 1001015
105 1001016
105 1001017
106 1001018
Note that there can be unlimited branch and customers, the query must work not only this case.
In this case the accepted result is:
100 103 104 105 106
2 1 3 2 1
Example SQL DATA
select '100' BranchName,'1001010' CustomerNo from dual UNION ALL
select '100' BranchName,'1001011' CustomerNo from dual UNION ALL
select '103' BranchName,'1001012' CustomerNo from dual UNION ALL
select '104' BranchName,'1001013' CustomerNo from dual UNION ALL
select '104' BranchName,'1001014' CustomerNo from dual UNION ALL
select '104' BranchName,'1001015' CustomerNo from dual UNION ALL
select '105' BranchName,'1001016' CustomerNo from dual UNION ALL
select '105' BranchName,'1001017' CustomerNo from dual UNION ALL
select '106' BranchName,'1001018' CustomerNo from dual
What about this solution. Without no table creation, just set the v_sql parameter.
And the output is
You can use this selection:
In general it is not professional to use selection for every number in
branchname
.I think it is possible, though quite complicated, to write a pipelined table function that returns a variable structure. Your pipeline table function will use the Oracle Data Cartridge interface and the magic of the AnyDataSet type to return a dynamic structure at runtime. You can then use that in subsequent SQL statements as if it was a table, i.e.
A couple more references that discuss the same sample implementation
Method4. After downloading and installing the open source PL/SQL code, here is a complete implementation:
If you just want to report the results somewhere, you may use a cursor for the select statement:
Looping through the cursor you may get your values.
here is my sample:
This will get it in rows (rather than columns):
(Note: you can omit the
DISTINCT
keyword if there will never be repeats of thebranchname
,customerno
pair.)Without knowing what the branch names are you are could only do a dynamic pivot.
It would be much simpler to take the output of the above query (in row format) and transpose it in whatever front-end you are using to access the database.
From comments:
No, you don't need it in column format in SQL. You can put it into excel in row format and then use excel's
TRANSPOSE
function to convert it (very simply) to columns without having to implement a complicated dynamic SQL solution.This query gives the output in xml format. The whole xml data will be contained in the field that the query results(The query has only single row-sinlge column output). The next step is to parse the xml data and display it in tabular form.