Generating rows from single column
hi All,
I need u guys help for following issue.
Supose i have a table called parameters with following columns
TABLE - PARAMETERS;
desc PARAMETERS;
customer_id number(9)
params varchar2(3500)
say againt a customer id 100 data stored in params like below
X;Y;PP;CH;KK;RX:KY
My question is ..is it possible to have a SQL query that can split into multiple rows like below.
100 X
100 Y
100 PP
100 CH
100 KK
100 RX
100 KY
Basically i am looking for a solution with a general sql query with out writing plsql.
Thanks
I had the following in an old code archive which does what you want - assuming the semi-colon is the separator.... (hope the code tags format this correctly!)
with tmp as (
SELECT 100 as customer_id, 'X;Y;PP;CH;KK;RX;KY' as params FROM DUAL
UNION ALL
SELECT 200 as customer_id, 'UI;RT;QE' as params FROM DUAL
select t1.*,
trim(replace(substr(t1.params,mstart,(t2.mlevel-mstart)+1),';','')) as data_split
from tmp t1
join (
select customer_id,substr(params,level,1) as mchar,
level as mlevel,nvl(lag(level) over (partition by customer_id order by level),0)+1 as mstart
from tmp
where substr(params,level,1)=';'
or level=length(params)
connect by level<=length(params)
and prior customer_id=customer_id
AND PRIOR DBMS_RANDOM.STRING ('p', 10) IS NOT NULL
) t2
on t1.customer_id=t2.customer_id
Similar Messages
-
Find MIN, MAX of multiple rows from multiple columns
Hello,
I need to figure out how to pull the MIN/MAX of multiple rows from multiple columns into one column. Even if some are NULL/blank.
For Example: (C: Column, R: Row, N - NULL/Blank)
C:____1____2____3____ 4____Max
R:____20___22___13____4____*22*
R:____N____N____32____14___*32*
R:____N____12____N____N____*12*
That is, it always gives a value for MIN/MAX unless there are NO values in all the rows of the columns.
So if there is one value, it will select that for the MIN/MAX, as it's the smallest/biggest since there is nothing to compare it to.
Here is my current code:
CASE WHEN COLUMN 1 < COLUMN 2 THEN COLUMN 2 ELSE COLUMN 1 ENDHi Thank you for your feedback, unfortunately, I just found out that EVALUATE Function is disabled in our environment for security reasons, so the only other way I've discovered is this:
The problem is that none of the conditions in the case statement are met--so the column is set to null. You can add a WHEN statement (section 2 below) to catch the nulls. There are five cases to consider:
Case 1: begin insp > bad order
Case 2: begin insp < bad order
Case 3: bad order only (begin insp is NULL)
Case 4: begin insp only (bad order is NULL)
Case 5: both begin insp is NULL and bad order is NULL
1) If bgn-crm-insp-ob > report-bo-ob then bgn-crm-insp-ob
(Case 1)
CASE WHEN filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'bgn-crm-insp-ob') > filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'report-bo-ob') THEN filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'bgn-crm-insp-ob')
2) If report-bo-ob is NULL then bgn-crm-insp-ob
(Case 4, 5) for case 5, you will get NULL
WHEN filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'report-bo-ob') IS NULL THEN filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'bgn-crm-insp-ob')
3) Else report-bo-ob
(Cases 2, 3)
ELSE filter ("- Terminal Task Measures"."Task Reported DateTime (Local)" using "Task Detail"."Task Code" = 'report-bo-ob') END
Hopefully this works, I'll give feedback if it does, or if you have any further suggestions please submit, again, THANK YOU SO MUCH ANYWAYS! -
How to join 2 rows under single column header
i want to join 2 or more rows under a single column header. as shown "container details" is the column name with "h", "w", and "s" and the sub column names. so my header should contain all these four names and my 3 rows under h,w and s should be clubed under this container details.
anyone help me out. thanks in advance.
container details
| h | w | sBummer, I just tried the link (which I saved from a couple months ago) and it doesn't work. This was a great site for showing how to do various things in Swing. Sorry for the bad link. Maybe someone saved the sites info or knows where it may have moved. Dang...
-
Hi All
Need some assistance, i have a table where i want the output to be a single column
ex: select from t1;*
query output_
rownum col_1
1 8217
2 6037
3 5368
4 5543
5 5232
i would like the result to be : *8217,6037,5368,5543,5232*
thanks for your help in advance.
i did look on the web but can't find a solution that is easily understood.Hi,
855161 wrote:
thanks for responding quickly.
the link example seems not to work for me:
below is the information you have requested:Below is some of what I requested. The CREATE TABLE and INSERT statements seem to be missing.
1. duplicate values have no effect
2. list doesn't need any order
3. Version 10.2.0.5.0 For that, I recommend the user-defined aggregate function called STRING_AGG in the Oracle Base page, but called STRAGG by most of the people who use it. You have to copy and run about 60 lines of code from the Oracle Base page, or from AskTom one time, but once you have it installed, the job is as simple as
SELECT MIN (rnum) AS rnum -- ROWNUM isn't a good column name, since it's the same as a pseudo-column
, STRAGG (count_1) AS count_1_list
FROM table_x
;Hundreds of other jobs you have in the future will be just as easy, and you won't have to go through the installation process again.
Relevant information:
1. table columns : count_1
all rows should become a single row with ',' in between
example:
select * from t1;
output:
Rownum count_1
1 8217
2 6037
3 5368
4 5543
5 5232
Desired results :
Rownum count_1
1 8217, 6037, 5368, 5543, 5232
Edited by: 855161 on Dec 11, 2012 1:25 PMThe main problem with STRAGG is that it doesn't create a list in order. You said that's not an issue in this case, but if you ever do need output in order, then the best option in Oracle 10 is the SYS_CONNECT_BY_PATH technique. The main Oracle-Base page shows how to use SYS_CONNECT_BY_PATH in Oracle 9. Of course, that works in all later versions too, but in version 10 a simpler way, using CONNECT_BY_ISLEAF, became available. See the Oracle-Base Comments Page for the eaiser Oracle 10 technique. -
Convert different rows into single column
DB : 11.1.0.7
OS : Solaris Sparc 5.10
I have one query which is joining few tables and giving me output like below.
personnum orgnm
======= =======
6 Keyholder
9 Sales
3 Mgmt
I would like to convert that into single column like below.
col1
========
6,Keyholder,9,Sales,3,Mgmt
I have tried with pivot and decode, but not getting resule which I am exepcting. Any suggesstions ?yashwanth437 wrote:
listagg() function could work.LISTAGG is not available in 11.1. It was introduced in 11.2.
Anyway, XML solution:
with sample_table as (
select 6 personnum,'Keyholder' orgnm from dual union all
select 9,'Sales' from dual union all
select 3,'Mgmt' from dual
select rtrim(xmlagg(xmlelement(e,personnum || ',' || orgnm,',').extract('//text()')),',') col1
from sample_table
COL1
6,Keyholder,9,Sales,3,Mgmt
SQL> SY. -
Convert rows to single column using t-sql
Hi All,
I have a table with 7 columns, et say..
ID ,PatientName,Date,Time,Room_Num ,Specialized, DoctorName
My source date looks like this..
ID PatientName Date Time Room_Num Specialized DoctorName
1 Sam 10/02/2010 10:00 4 Heart
John
1 Sam 10/02/2010 10:00 4 Lungs
Harris
2 Jones 11/12/2011 11:00 1 Lungs
Bob
3 Jim 12/05/2001 01:00 2 Kidney
Greg
3 Jim 12/05/2001 09:00 2 Eye
Roby
1 Sam 12/22/2010 11:00 1 Heart
John
1 Sam 12/22/2010 11:00 1 Lungs
Harris
My out put should look like this..
ID PatientName Date DoctorName
1 Sam 10/02/2010 John,Harris ( Need to be in 1 row because - ID, PatientName, Date is same)
2 Jones 11/12/2011 Bob ( Need to show as it is due to no repeatition
of ID)
3 Jim 12/05/2001 Greg,Roby ( Need to be in 1 row because - ID, PatientName,
Date is same)
1 Sam 12/22/2010 John,Harris ( Need to be in 1 row because - ID, PatientName, Date is same)
I am using below query to get above results but I am getting wrong results..Need some help in tweaking the query...
SELECT DISTINCT ID ,PatientName , Date
,STUFF(( SELECT ',' + DoctorName
FROM SampleTable ST1
WHERE ST1.ID=ST2.ID
FOR XML PATH('')),1,1,' ') AS DoctorName
FROM SampleTable1 ST2
GROUP BY ID ,PatientName , Date
With above query I am getting results like this...
ID PatientName Date DoctorName
1 Sam 10/02/2010 John,Harris ,John,Harris ( here John,Harris are repeating twice because of 4th row)
2 Jones 11/12/2011 Bob
3 Jim 12/05/2001 Greg,Roby
1 Sam 12/22/2010 John,Harris ,John,Harris ( here John,Harris are repeating twice because of 1st row)
Create table statement:
Create table SampleTable
ID Int null, PatientName varchar(25) null, Date datetime null, Time varchar(10) null, Room_Num int null, Specialized varchar(20) null, DoctorName varchar(20) null
Insert statement:
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam','10/02/2010' ,'10:00',4 ,'Heart','John')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1, 'Sam','10/02/2010' ,'10:00' , 4 , 'Lungs','Harris')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 2, 'Jones' ,'11/12/2011' , '11:00',1, 'Lungs', 'Bob')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 3,'Jim' ,'12/05/2001' , '01:00',2,'Kidney' , 'Greg')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 3,'Jim' ,'12/05/2001' , '09:00',2,'Eye' , 'Roby')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam' ,'12/22/2010' , '11:00',1,'Heart', 'John')
Insert into sampletable(ID,PatientName,Date,Time,Room_Num,Specialized,DoctorName) Values ( 1,'Sam', '12/22/2010' , '11:00',1 , 'Lungs','Harris')
I need help to tweak my query.
Thanks,
RH
sqlWITH cte AS(
SELECT [ID]
,[PatientName]
,[Date]
,[Time]
,[Room_Num]
,[Specialized]
,[DoctorName]
,ROW_NUMBER() OVER(PARTITION BY [ID],[PatientName],[Date] ORDER BY Time) as RowID
FROM [test].[dbo].[SampleTable]
SELECT
cte.[ID]
,cte.[PatientName]
,CAST(cte.[Date] as DATE) as [Date]
,STUFF((SELECT ',' + c.[DoctorName]
FROM cte c
WHERE c.ID=cte.ID AND c.PatientName=cte.[PatientName] AND c.[Date]=cte.[Date]
FOR XML PATH(''),TYPE).value('.','varchar(max)')
,1,1,'') AS [DoctorName]
FROM cte
WHERE cte.RowID=1 -
Creating chart from single column of multiple tables in Numbers '09
I have multiple tables (spread across multiple sheets) in my document. In column B of each table is a name. The other columns contain other categorized data. Each table has a variable number of rows, but each name is unique within a table. A particular name in any one table may or may not occur in another.
What I want to do is create a chart that shows the total number of times each unique name occurs across all the tables. Not really sure how to do this...
I would also like to be able to sort the chart from highest to lowest.
Message was edited by: Sir ReginaldThat won't quite work, as I have hundreds of names to process. It was a good starting point though. Here's what I had to do:
1) create a new table (mynames) containing all the names in mynames::A
2) in mynames::B1 put the formula =SUM(COUNTIF(Table 1::A, A1), COUNTIF(Table 2::A, A1), ...)
3) Select column mynames::B and then choose *INSERT -> Fill Down* from the menu
It becomes a bit tedious to have to update the formula and refill the column every time I add another data table. Imagine if I had hundreds of tables to enter. Hmmm....
I currently have one table per sheet, but if I were to move all the tables onto one sheet, categorize a column, and then collapse all the categories, that wouldn't take up too much space on one sheet. Say I had 100 tables, I could then reduce the formula to:
=COUNTIF(Table 1:Table 100::A, A1)
I would also have to make sure to place the mynames table before Table 1 in the table list. All in all, much less of a hassle to add new table data.
Hopefully, Apple will add multi-sheet spanning collections, in the same way you can do multi-table collections now.
Message was edited by: Sir Reginald -
Need different rows from single query based on condition
Hi,
I have a table with 100 rows that holds employees and their roles.
I need to write a SQL(not a PL/SQL block) as below
1. When employee with role 'VP' logs in, the query should return all the 100 rows.
2. When employee with role 'MGR' logs in, the query should return only those rows whose MGR is the logged in employee.
3. When employee with role 'SALE_EXEC' logs in, it should return single rows corresponding to this SALE_EXEC.
My requirement here is to get these outputs from a single query.
Can anyone please help me with this.
Thanks,
Vivek.use vpd
New Policy Groups
When adding the policy to a table, view, or synonym, you can use the DBMS_RLS.ADD_GROUPED_POLICY interface to specify the group to which the policy belongs. To specify which policies will be effective, you add a driving context using the DBMS_RLS.ADD_POLICY_CONTEXT interface. If the driving context returns an unknown policy group, then an error is returned.
If the driving context is not defined, then all policies are executed. Likewise, if the driving context is NULL, then policies from all policy groups are enforced. In this way, an application accessing the data cannot bypass the security setup module (which sets up application context) to avoid any applicable policies.
You can apply multiple driving contexts to the same table, view, or synonym, and each of them will be processed individually. In this way, you can configure multiple active sets of policies to be enforced.
Consider, for example, a hosting company that hosts Benefits and Financial applications, which share some database objects. Both applications are striped for hosting using a SUBSCRIBER policy in the SYS_DEFAULT policy group. Data access is partitioned first by subscriber ID, then by whether the user is accessing the Benefits or Financial applications (determined by a driving context). Suppose that Company A, which uses the hosting services, wants to apply a custom policy which relates only to its own data access. You could add an additional driving context (such as COMPANY A SPECIAL) to ensure that the additional, special policy group is applied for data access for Company A only. You would not apply this under the SUBSCRIBER policy, because the policy relates only to Company A, and it is more efficient to segregate the basic hosting policy from other policies.
How to Implement Policy Groups
To create policy groups, the administrator must do two things:
Set up a driving context to identify the effective policy group.
Add policies to policy groups as required.
The following example shows how to perform these tasks.
Note:
You need to set up the following data structures for the examples in this section to work:
DROP USER finance CASCADE;
CREATE USER finance IDENTIFIED BY welcome2;
GRANT RESOURCE TO apps;
DROP TABLE apps.benefit;
CREATE TABLE apps.benefit (c NUMBER);
Step 1: Set Up a Driving Context
Begin by creating a namespace for the driving context. For example:
CREATE CONTEXT appsctx USING apps.apps_security_init;
Create the package that administers the driving context. For example:
CREATE OR REPLACE PACKAGE apps.apps_security_init IS
PROCEDURE setctx (policy_group VARCHAR2);
END;
CREATE OR REPLACE PACKAGE BODY apps.apps_security_init AS
PROCEDURE setctx ( policy_group varchar2 ) IS
BEGIN
REM Do some checking to determine the current application.
REM You can check the proxy if using the proxy authentication feature.
REM Then set the context to indicate the current application.
DBMS_SESSION.SET_CONTEXT('APPSCTX','ACTIVE_APPS', policy_group);
END;
END;
Define the driving context for the table APPS.BENEFIT.
BEGIN
DBMS_RLS.ADD_POLICY_CONTEXT('apps','benefit','APPSCTX','ACTIVE_APPS');
END;
Step 2: Add a Policy to the Default Policy Group.
Create a security function to return a predicate to divide the data by company.
CREATE OR REPLACE FUNCTION by_company (sch varchar2, tab varchar2)
RETURN VARCHAR2 AS
BEGIN
RETURN 'COMPANY = SYS_CONTEXT(''ID'',''MY_COMPANY'')';
END;
Because policies in SYS_DEFAULT are always executed (except for SYS, or users with the EXEMPT ACCESS POLICY system privilege), this security policy (named SECURITY_BY_COMPANY), will always be enforced regardless of the application running. This achieves the universal security requirement on the table: namely, that each company should see its own data regardless of the application that is running. The function APPS.APPS_SECURITY_INIT.BY_COMPANY returns the predicate to make sure that users can only see data related to their own company:
BEGIN
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','SYS_DEFAULT',
'security_by_company',
'apps','by_company');
END;
Step 3: Add a Policy to the HR Policy Group
First, create the HR group:
CREATE OR REPLACE FUNCTION hr.security_policy
RETURN VARCHAR2
AS
BEGIN
RETURN 'SYS_CONTEXT(''ID'',''TITLE'') = ''MANAGER'' ';
END;
The following creates the policy group and adds a policy named HR_SECURITY to the HR policy group. The function HR.SECURITY_POLICY returns the predicate to enforce security on the APPS.BENEFIT table:
BEGIN
DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','HR');
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','HR',
'hr_security','hr','security_policy');
END;
Step 4: Add a Policy to the FINANCE Policy Group
Create the FINANCE policy:
CREATE OR REPLACE FUNCTION finance.security_policy
RETURN VARCHAR2
AS
BEGIN
RETURN ('SYS_CONTEXT(''ID'',''DEPT'') = ''FINANCE'' ');
END;
Create a policy group named FINANCE and add the FINANCE policy to the FINANCE group:
BEGIN
DBMS_RLS.CREATE_POLICY_GROUP('apps','benefit','FINANCE');
DBMS_RLS.ADD_GROUPED_POLICY('apps','benefit','FINANCE',
'finance_security','finance', 'security_policy');
END;
As a result, when the database is accessed, the application initializes the driving context after authentication. For example, with the HR application:
execute apps.security_init.setctx('HR');
Validating the Application Used to Connect to the Database
The package implementing the driving context must correctly validate the application that is being used to connect to the database. Although the database always checks the call stack to ensure that the package implementing the driving context sets context attributes, inadequate validation can still occur within the package.
For example, in applications where database users or enterprise users are known to the database, the user needs the EXECUTE privilege on the package that sets the driving context. Consider a user who knows that:
The BENEFITS application allows more liberal access than the HR application
The setctx procedure (which sets the correct policy group within the driving context) does not perform any validation to determine which application is actually connecting. That is, the procedure does not check either the IP address of the incoming connection (for a three-tier system) or the proxy_user attribute of the user session.
Such a user could pass to the driving context package an argument setting the context to the more liberal BENEFITS policy group, and then access the HR application instead. Because the setctx does no further validation of the application, this user bypasses the normally more restrictive HR security policy.
By contrast, if you implement proxy authentication with VPD, then you can determine the identity of the middle tier (and the application) that is actually connecting to the database on behalf of a user. In this way, the correct policy will be applied for each application to mediate data access.
For example, a developer using the proxy authentication feature could determine that the application (the middle tier) connecting to the database is HRAPPSERVER. The package that implements the driving context can thus verify whether the proxy_user in the user session is HRAPPSERVER. If so, then it can set the driving context to use the HR policy group. If proxy_user is not HRAPPSERVER, then it can disallow access.
In this case, when the following query is executed
SELECT * FROM APPS.BENEFIT;
Oracle Database picks up policies from the default policy group (SYS_DEFAULT) and active namespace HR. The query is internally rewritten as follows:
SELECT * FROM APPS.BENEFIT WHERE COMPANY = SYS_CONTEXT('ID','MY_COMPANY') and SYS_CONTEXT('ID','TITLE') = 'MANAGER';
How to Add a Policy to a Table, View, or Synonym
The DBMS_RLS package enables you to administer security policies by using its procedures for adding, enabling, refreshing, or dropping policies, policy groups, or application contexts. You need to specify the table, view, or synonym to which you are adding a policy, as well as the data pertinent to that policy, such as the policy name. Such data also includes names for the policy group and the function implementing the policy. You can also specify the types of statements the policy controls (SELECT, INSERT, UPDATE, DELETE, CREATE INDEX, or ALTER INDEX).
for more you can refer to
http://download-west.oracle.com/docs/cd/B19306_01/network.102/b14266/apdvcntx.htm -
Converting multiple column rows into single column
Hi all Below is my requirement, can you anybody help me solve it. CREATE TABLE TYPE ( c1_type VARCHAR2 (10), c2_type VARCHAR2 (10), c3_type VARCHAR2 (10), c4_type VARCHAR2 (10), c5_type VARCHAR2 (10), c6_type VARCHAR2 (10), c7_type VARCHAR2 (10), c8_type VARCHAR2 (10), c9_type VARCHAR2 (10)); INSERT INTO TYPE VALUES ('Region_D', 'Region_E', 'Region_F', 'Region_D', 'Region_E', 'Region_D', 'Region_M', 'Region_D', 'Region_E'); commit; Acutal output on the below query select * from type; C1_TYPE C2_TYPE C3_TYPE C4_TYPE C5_TYPE C6_TYPE C7_TYPE C8_TYPE C9_TYPE Region_D Region_E Region_F Region_D Region_E Region_D Region_M Region_D Region_E Acutal i am expecting the below output,how to make it using query or using oracle built in function. Region_D Region_D Region_D Region_D Region_E Region_E Region_E Region_F Region_M
Hi,
So, you want to put the column values in alphabetic order, with the earliest value in c1_type and the last in c9_type, is that it?
The fact that you even want to do this says that this is a bad table design. If sorting the values makes sense, then putting them all in the same column on 9 different rows (rather than 9 different columns on 1 row) makes sense.
If you're stuck with the current design, then use SELECT ... UNPIVOT to put them on separate rows, then use the analytic ROW_NUMBER function to assign numbers 1-9 to each value, and finally use SELECT ... PIVOT to put them back into 1 row in that order. If you're not familiar with the built-in UNPIVOT and PIVOT features, look them up in the SQL Language manual, and see the forum FAQ:
https://forums.oracle.com/message/9362005
If you get stuck, post your best attempt (formatted), the exact results you want (formatted), and your Oracle version (e.g. 11.2.0.2.0).
Also, TYPE is an Oracle keyword, so it's not a good table name. Use something like location_type instead. -
Concatenating multiple rows from asingle column
hi,
Could anyone help me in writing a query for following
I have columns
A B
1 a
1 b
1 c
2 d
2 e
3 f
3 g
O/p
C
1 abc,
2 de,
3 fg
can anyone help me out in writing this ...I appriciate it.
Thanks,SELECT A,
REPLACE(SYS_CONNECT_BY_PATH(B,','),',') B
FROM (
SELECT A,
B,
ROW_NUMBER() OVER(PARTITION BY A ORDER BY B) RN,
COUNT(*) OVER(PARTITION BY A) CNT
FROM TBL
WHERE RN = CNT
START WITH RN = 1
CONNECT BY A = PRIOR A
AND RN = PRIOR RN + 1
ORDER BY A
/SY. -
Count of rows from different Columns
SELECT (SELECT COUNT (empno) empno
FROM emp) empno, (SELECT COUNT (mgr) mgr
FROM emp) mgr, (SELECT COUNT (sal) sal
FROM emp
WHERE sal > 2000) sal
FROM DUAL;Hi friends
Please let me know any better solutions for this query..??user10594152 wrote:
Please let me know any better solutions for this query..??Why not just..
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
14 rows selected.
SQL> ed
Wrote file afiedt.buf
1 select count(empno) as emps
2 , count(mgr) as mgrs
3 , sum(case when sal > 2000 then 1 else 0 end) as sals
4* from emp
SQL> /
EMPS MGRS SALS
14 13 6
SQL> -
How to convert rows into single columns in Oracle?
I have table with data like shown below in Oracle database.
P_COLUMN
COLUMN_1
COLUMN_2
COLUMN_3
COLUMN_ 4
COLUMN_5
COLUMN_6
COLUMN_7
COLUMN_8
COLUMN_9
COLUMN_10
1
A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
1
B1
B2
B3
B4
B5
B6
B7
B8
B9
B10
1
C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
2
AA1
AA2
AA3
AA4
AA5
AA6
AA7
AA8
AA9
AA10
2
BB1
BB2
BB3
BB4
BB5
BB6
BB7
BB8
BB9
BB10
I need a query to get one row based on P_COLUMN's value i.e. for P_COLUMN =1, below should be output :-
C_1
C_2
C_3
C_4
C_5
C_6
C_7
C_8
C_9
C_10
C_11
C_12
C_13
C_14
C_15
C_16
C_17
C_18
C_19
C_20
C_21
C_22
C_23
C_24
C_25
C_26
C_27
C_ 28
C_29
C_30
C_31
1
A1
A2
A3
A4
A5
A6
A7
A8
A9
A10
B1
B2
B3
B4
B5
B6
B7
B8
B9
B10
C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
2
AA1
AA2
AA3
AA4
AA5
AA6
AA7
AA8
AA9
AA10
BB1
BB2
BB3
BB4
BB5
BB6
BB7
BB8
BB9
BB10
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
NULL
i searched google and found PIVOT, CROSS JOIN etc but could not use those keyword properly.
Thanks in advance.
Note - My DB client version is 11g.Since you have 11G, here's an alternative with the PIVOT clause.
First, set up test data with up to 10 rows:
CREATE TABLE T(P1,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10) AS SELECT
1,1,2,3,4,5,6,7,8,9,10 FROM DUAL;
INSERT INTO T
WITH DATA AS (SELECT LEVEL*10 N FROM DUAL CONNECT BY LEVEL <= 9)
SELECT P1, C1+N, C2+N, C3+N, C4+N, C5+N, C6+N, C7+N, C8+N, C9+N, C10+N
FROM T, DATA;
INSERT INTO T
SELECT P1+1,C1,C2,C3,C4,C5,C6,C7,C8,C9,C10
FROM T
WHERE C1 <= 11;
select * from t order by p1,c1;
P1
C1
C2
C3
C4
C5
C6
C7
C8
C9
C10
1
1
2
3
4
5
6
7
8
9
10
1
11
12
13
14
15
16
17
18
19
20
1
21
22
23
24
25
26
27
28
29
30
1
31
32
33
34
35
36
37
38
39
40
1
41
42
43
44
45
46
47
48
49
50
1
51
52
53
54
55
56
57
58
59
60
1
61
62
63
64
65
66
67
68
69
70
1
71
72
73
74
75
76
77
78
79
80
1
81
82
83
84
85
86
87
88
89
90
1
91
92
93
94
95
96
97
98
99
100
2
1
2
3
4
5
6
7
8
9
10
2
11
12
13
14
15
16
17
18
19
20
Now the SELECT statement using PIVOT:
SELECT * FROM (
SELECT T.*,
ROW_NUMBER() OVER (
PARTITION BY P1
ORDER BY C1,C2,C3,C4,C5,C6,C7,C8,C9,C10
) RN
FROM T
PIVOT(
MAX(C1) C1, MAX(C2) C2, MAX(C3) C3, MAX(C4) C4, MAX(C5) C5,
MAX(C6) C6, MAX(C7) C7, MAX(C8) C8, MAX(C9) C9, MAX(C10) C10
FOR RN IN (1 R1,2 R2,3 R3,4 R4,5 R5,6 R6,7 R7,8 R8,9 R9,10 R10)
P1
R1_C1
R1_C2
R1_C3
R1_C4
R1_C5
R1_C6
R1_C7
R1_C8
R1_C9
R1_C10
R2_C1
R2_C2
R2_C3
R2_C4
R2_C5
R2_C6
R2_C7
R2_C8
R2_C9
R2_C10
R3_C1
R3_C2
R3_C3
R3_C4
R3_C5
R3_C6
R3_C7
R3_C8
R3_C9
R3_C10
R4_C1
R4_C2
R4_C3
R4_C4
R4_C5
R4_C6
R4_C7
R4_C8
R4_C9
R4_C10
R5_C1
R5_C2
R5_C3
R5_C4
R5_C5
R5_C6
R5_C7
R5_C8
R5_C9
R5_C10
R6_C1
R6_C2
R6_C3
R6_C4
R6_C5
R6_C6
R6_C7
R6_C8
R6_C9
R6_C10
R7_C1
R7_C2
R7_C3
R7_C4
R7_C5
R7_C6
R7_C7
R7_C8
R7_C9
R7_C10
R8_C1
R8_C2
R8_C3
R8_C4
R8_C5
R8_C6
R8_C7
R8_C8
R8_C9
R8_C10
R9_C1
R9_C2
R9_C3
R9_C4
R9_C5
R9_C6
R9_C7
R9_C8
R9_C9
R9_C10
R10_C1
R10_C2
R10_C3
R10_C4
R10_C5
R10_C6
R10_C7
R10_C8
R10_C9
R10_C10
1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 -
Defining 100 columns from single column
hi all,
i need to write an sp which returns many columns
i have code ,name,candidates,mark(0-100)
these are my columns in a table..
now i need to calculate columns 0-100 which mark having how many students..like
code name [ MARKS- 1] [MARK- 2] [
3] [ 4] [5 ] -----------[100]
01 eng 10CANDIDATES 2
10 64 44--------------98
02 BEG 12CANDIDATES 0
12 77 98 21
FOR THIS I WROTE CODE LIKE
SELECT Name,Code,Mark,CANDIDATES
INTO #tmp
FROM TABLENAME
WHERE (CONDITION)
SELECT
Name,Code
,[1] = SUM(CASE WHEN Mark=1 THEN Nos ELSE 0 END)
,[2] = SUM(CASE WHEN Mark=2 THEN Nos ELSE 0 END)
,[3] = SUM(CASE WHEN Mark=3 THEN Nos ELSE 0 END)
,[4] = SUM(CASE WHEN Mark=4 THEN Nos ELSE 0 END)
,[5]= SUM(CASE WHEN Mark=5 THEN Nos ELSE 0 END)
,[6] = SUM(CASE WHEN Mark=6THEN Nos ELSE 0 END)
,[7] = SUM(CASE WHEN Mark=7 THEN Nos ELSE 0 END)
,[8]= SUM(CASE WHEN Mark=8 THEN Nos ELSE 0 END)
,[9]= SUM(CASE WHEN Mark=9 THEN Nos ELSE 0 END)
,[10]= SUM(CASE WHEN Mark=10 THEN Nos ELSE 0 END)
---SO ON UPTO 100---------------------------------------------
FROM #tmp
GROUP BY Name,Code
NOW ITS too big code to define upto 100, so how caan i define in easiest way like any loop way? and simple code..pls help
thanks in advance..
luckyhi all,
i need to write an sp which returns many columns
i have code ,name,candidates,mark(0-100)
these are my columns in a table..
now i need to calculate columns 0-100 which mark having how many students..like
code name [ MARKS- 1] [MARK- 2] [
3] [ 4] [5 ] -----------[100]
01 eng 10CANDIDATES 2
10 64 44--------------98
02 BEG 12CANDIDATES 0
12 77 98 21
FOR THIS I WROTE CODE LIKE
SELECT Name,Code,Mark,CANDIDATES
INTO #tmp
FROM TABLENAME
WHERE (CONDITION)
SELECT
Name,Code
,[1] = SUM(CASE WHEN Mark=1 THEN Nos ELSE 0 END)
,[2] = SUM(CASE WHEN Mark=2 THEN Nos ELSE 0 END)
,[3] = SUM(CASE WHEN Mark=3 THEN Nos ELSE 0 END)
,[4] = SUM(CASE WHEN Mark=4 THEN Nos ELSE 0 END)
,[5]= SUM(CASE WHEN Mark=5 THEN Nos ELSE 0 END)
,[6] = SUM(CASE WHEN Mark=6THEN Nos ELSE 0 END)
,[7] = SUM(CASE WHEN Mark=7 THEN Nos ELSE 0 END)
,[8]= SUM(CASE WHEN Mark=8 THEN Nos ELSE 0 END)
,[9]= SUM(CASE WHEN Mark=9 THEN Nos ELSE 0 END)
,[10]= SUM(CASE WHEN Mark=10 THEN Nos ELSE 0 END)
---SO ON UPTO 100---------------------------------------------
FROM #tmp
GROUP BY Name,Code
NOW ITS too big code to define upto 100, so how caan i define in easiest way like any loop way? and simple code..pls help
thanks in advance..
lucky
Please post the create table script and sample data.
- please mark correct answers -
Convert Rows into single column
Hi,
My employee details table has data like below,
employee_id position department
100 technician 50
100 IT 80
101 Accountant 60
101 Accounting Manager 70
Now i want to covert the rows into column. So my output should be like this.
output:
employee_id position department position1 department1
100 technician 50 IT 80
101 Accountant 60 Accounting Manager 70
Help me on this
Edited by: Vi on Mar 22, 2012 5:36 AM
Edited by: Vi on Mar 22, 2012 5:36 AMIgor.M wrote:
http:// website link removed /t_converting_rows_columns.htm
Please don't post links to commercial websites that are only trying to sell their products and services. It breaches the terms of use of the forums.
There are usually more suitable websites giving much more valuable information without all the self promotion (google adwords etc. are acceptable), or in the case of this particular question there is a FAQ post that relates to it...
{message:id=9360005} -
Combine two rows in single column data
hi,
I have an requirement
for ex:
Division Resourcename PRojectname Projectstartdate Projectenddate allocated percentage
development A one '01/01/2014' '03/31/2014'
100%
development B one '01/01/2014' '03/31/2014'
100%
development C one '01/01/2014' '03/31/2014'
100%
development D one '01/01/2014' '03/31/2014'
100%
development E one '01/01/2014' '01/31/2014'
25%
development E one '02/01/2014' '03/31/2014'
25%
In the above "Resource E have multiple dates ,will work on separate dates on single project,but the resource allocated percentage will be always same(ie)=25%,so the report output look like
Division Resourcename PRojectname Projectstartdate Projectenddate allocated percentage
development A one '01/01/2014' '03/31/2014'
100%
development B one '01/01/2014' '03/31/2014'
100%
development C one '01/01/2014' '03/31/2014'
100%
development D one '01/01/2014' '03/31/2014'
100%
development E one '01/01/2014' '01/31/2014'
25%
'02/01/2014' '03/31/2014'
the above SSRS report output look after grouping on division,resource.
this same output i need from sql query.how to achieve this.
Thanks
r.bBhupesh, I do not have any idea how your actual data would look like. So the below snippet can
only taken as reference not as an actual.
[Join condition, CASE...WHEN everything would change as per your actual data]
Try the below:
create table Bhupesh_test(Division varchar(50), Res_Name varchar(50), Proj_Name varchar(50), startdate date, enddate date, allocated int)
Insert into Bhupesh_test Values
('development','A','one', '01/01/2014','03/31/2014',100),
('development','B','one', '01/01/2014','03/31/2014',100),
('development','C','one', '01/01/2014','03/31/2014',100),
('development','D','one', '01/01/2014','03/31/2014',100),
('development','E','one', '01/01/2014','01/31/2014',25),
('development','E','one', '02/01/2014','03/31/2014',25)
;With cte
as
Select *, ROW_NUMBER()OVER(Partition by Division,Res_Name,Proj_Name Order by startdate)Rn
From Bhupesh_test
Select Division,Res_Name,Proj_Name,startdate,enddate,allocated From
Select Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
and A.startdate <>B.startdate Then NULL Else A.Division end Division,
Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
and A.startdate <>B.startdate Then NULL Else A.Res_Name end Res_Name,
Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
and A.startdate <>B.startdate Then NULL Else A.Proj_Name end Proj_Name,
Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
Then A.startdate Else B.startdate end startdate,
Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
AND A.startdate <> B.startdate Then A.enddate Else B.enddate end enddate,
Case when A.Division = B.Division and A.Res_Name = B.Res_Name and A.Proj_Name = B.Proj_Name
and A.startdate <>B.startdate Then NULL Else A.Allocated end Allocated,1 Ordered
From cte A
Inner join cte B on A.Rn = B.Rn+1 and A.Res_Name = B.Res_Name
Union All
Select Division,Res_Name,Proj_Name,startdate,enddate,allocated,0 From cte A where Rn=1
) A
Order by Ordered
Drop table Bhupesh_test
Maybe you are looking for
-
Problem while using SELECT Operation in DB Adapter
Hi, I am trying to use the DB Adapter with SELECT operation on one of the tables in our database. The query looks some thing like, SELECT ORDER_HEADER_ID, SHIPPING_GRP_ID, ATG_SHIPPING_GROUP_ID, SO_HEADER_ID, ORDER_NUMBER, SHIP_ITEM_ID FROM <TABLE_NA
-
my starts siri by it self and when i desable siri so voice control starts talking even i didn't touch my fone its operating by its self in the middle of talking on fone or not using it. sometimes the home key is not working at all. it stuck and i hav
-
Can you move a photo that was emailed to "Photos"
If someone emails me a photo can I move it to the iPhone's Photos albums to store and keep on my phone?
-
Can I upgrade to CS6 from Lightroom 4.2 or Adobe Premier Elements?
Can I upgrade to CS6 from Lightroom 4.2 or Adobe Premier Elements . . . or both?
-
Upload won't go over 9Mb?
Noticed recenrly that any speedtests I do.. the upload is showing the old 10Mb speeds.. I have reset ther router, reconnected the modem tried wireless and wired. Also the btwholesale checker says the profile is 20Mb? Any ideas?