Help for update query
Hi, How I can split the column of code_full_desc and update in code1,code2 and code3 column which are blank. It should be split after first hyphen.
create table #desc (code_full_desc char(20), code1 char(4),code2 char(4), code3 char(6))
insert into #desc values ('CCCCA_AAAA_99_ECTRA','','','')
insert into #desc values ('DDDDA_BBBB_88_TRACT','','','')
---Results should be
code_full_desc code1 code2 code3
CCCCA_AAAA_99_ECTRA AAAA 99 ECTRA
DDDDA_BBBB_88_TRACT BBBB 88 TRACT
create table #desc (code_full_desc char(20), code1 char(4),code2 char(4), code3 char(6))
insert into #desc values ('CCCCA_AAAA_99_ECTRA','','','')
insert into #desc values ('DDDDA_BBBB_88_TRACT','','','')
select * from #desc
;with mycte as
SELECT row_number() Over(Partition by code_full_desc Order by code_full_desc) rn, code_full_desc, S.a.value('(/H/r)[4]', 'VARCHAR(100)') AS splitVal4
, S.a.value('(/H/r)[3]', 'VARCHAR(100)') AS splitVal3
, S.a.value('(/H/r)[2]', 'VARCHAR(100)') AS splitVal2
, S.a.value('(/H/r)[1]', 'VARCHAR(100)') AS splitVal1
,code1,code2,code3
FROM
SELECT *,CAST (N'<H><r>' + REPLACE(code_full_desc, '_', '</r><r>') + '</r></H>' AS XML) AS [vals]
FROM #desc) d
CROSS APPLY d.[vals].nodes('/H/r') S(a)
Update mycte
set
code1=splitVal2,
code2=splitVal3,
code3=splitVal4
WHERE rn=1
select * from #desc
drop table #desc
Similar Messages
-
Just wanna ask help in update query
SELECT T1.ttl_cr_adjust_amt,T2.ttl_cr_adjust_amt
FROM invoice T1
,(SELECT bill_date
,acct_no
,sum(summ_amt) as ttl_cr_adjust_amt
FROM INV_ACCT_SUMM
WHERE summ_code='LSG02'
GROUP by bill_date,acct_no) T2
WHERE T1.bill_date=T2.bill_date
AND T1.acct_no=T2.acct_no
i want update T1.ttl_cr_adjust_amt= T2.ttl_cr_adjust_amt tht means i want give T2.ttl_cr_adjust_amt to T1.ttl_cr_adjust_amt the primary key for invoice is T1.bill_date,T1.acct_no
how to do update stament
i need efficent
thanks is can helpBe care, simpe UPDATE without WHERE clause will change ALL rows in
invoice table dispite are there any related data in inv_acc_summ.
(NOT tested !!!)
UPDATE invoice T1
SET T1.ttl_cr_adjust_amt = (SELECT sum(summ_amt)
FROM INV_ACCT_SUMM T2
WHERE summ_code='LSG02'
AND T1.bill_date=T2.bill_date
AND T1.acct_no=T2.acct_no
WHERE (t1.bill_date, t1.acc_no) IN
SELECT t2.bill_date, t2.acc_no
FROM INV_ACCT_SUMM t2
WHERE t2.summ_code='LSG02'
Rgds. -
Hi All,
I having block level 8000 records, I Scroll down from First record to last record it is takeing more time.
I Observed tkproof while scrolling two select statments are running..
1) pre-query block level
2) For update query
For update query -> How is is forming? Any Property or some else?
I am not able to find the second query..where it is forming..How to restrict the second query.
Query Array size - 10
Number of records buffered - 10
Number of records Displayed - 10
Query all records - No
Locking mode - Immediate
Key mode - Automatic
Version - Oracle 10g
Plz ........anyThe for update -query is generaetd by forms when its locking the record. If you didn't change anything in the record "by hand", check if there is some code in the POST-QUERY-trigger which forces the record to be locked. if its the POST-QUERY you can issue the following command to avoid the lock at the end of the POST-QUERY:
SET_RECORD_PROPERTY(:SYSTEM.TRIGGER_BLOCK, :SYSTEM.TRIGGER_RECORD, STATUS, QUERY_STATUS); -
Please Help for the Query
Hi frds please help me for the below query.What I want to do is to pull out the data from below table :-
date ticker indicator
03/13/2008 3IINFOTECH -8
03/18/2008 3IINFOTECH -4
03/25/2008 3IINFOTECH -5
03/27/2008 3IINFOTECH -3
as such :-
date ticker indicator
03/13/2008 3IINFOTECH -8
03/25/2008 3IINFOTECH -5
03/27/2008 3IINFOTECH -3
Here I want to find the Trend i.e either asc or desc order from the lowest indicator.
In the above sample data -8, -4, -5, -3 out of which I want the asc order data -8, -5, -3 and exclude -4 data.Because the asc order -8, -5, -3 will not follow.
So I want the data
date ticker indicator
03/13/2008 3IINFOTECH -8
03/25/2008 3IINFOTECH -5
03/27/2008 3IINFOTECH -3SQL> CREATE TABLE BORRAME(FECHA DATE, INDICA VARCHAR2(100));
Tabla creada.
SQL> INSERT INTO BORRAME VALUES(TO_DATE('03/13/2008','MM/DD/YYYY'), '3IINFOTECH -8');
1 fila creada.
SQL> INSERT INTO BORRAME VALUES(TO_DATE('03/18/2008','MM/DD/YYYY'), '3IINFOTECH -4');
1 fila creada.
SQL> INSERT INTO BORRAME VALUES(TO_DATE('03/25/2008','MM/DD/YYYY'), '3IINFOTECH -5');
1 fila creada.
SQL> INSERT INTO BORRAME VALUES(TO_DATE('03/27/2008','MM/DD/YYYY'), '3IINFOTECH -3');
1 fila creada.
SQL> COMMIT;
Validación terminada.
SQL>
SQL> SELECT FECHA, INDICA
2 FROM BORRAME
3 WHERE SUBSTR(INDICA,INSTR(INDICA,'-',1)+1,LENGTH(INDICA)) <> '4'
4 ORDER BY SUBSTR(INDICA,INSTR(INDICA,'-',1)+1,LENGTH(INDICA)) DESC;
FECHA
INDICA
13/03/08
3IINFOTECH -8
25/03/08
3IINFOTECH -5
27/03/08
3IINFOTECH -3
-
SELECT table_name FROM all_tables WHERE dropped = 'NO' and owner = 'test'
FOR UPDATE;
ERROR at line 1:
ORA-02030: can only select from fixed tables/views
ORA-06512: at line 9
ORA-06512: at line 16
Can any body help me out what is wrong in that query.
ThanxSELECT table_name FROM all_tables WHERE dropped = 'NO' and owner = 'test'
FOR UPDATE;What do you want to achieve from this?? Do you want to update the all_tables ?? :-) -
For Update Query from ORACLE Forms
Hi
We are using Oracle Forms 10g running with 10g database 10.2.0.1.0. We happend to see a query which is getting generated in AWR report like Select rowid, all_columns from TableName for Update of C1 Nowait. But no such query is really written in forms and we are aware that, Any query prefixed with rowid is definitely executing from Forms. But how the ForUpdate and Nowait clause is appended to the query.
We have checked the following properties in the database Block
*1) Locking Mode is set to Automatic*
*2) Update Changed Columns only is set to YES*
*3) Query all records is set to No (Though this particular property may not be relevant to the issue)*
What is the property or setting which might trigger such a query from ORACLE Forms with ForUpdate and Nowait clause.
Any ideas/suggestions on why such behaviour. Please have a healthy discussion on this. Thanks in advance.you can't dynamically add a query to the data model in reports.
You should look into the XML based customization of Oracle Reports. This will enable you to define a report dynamically by creating a definition in XML.
Also another option is to have the report with a query in it and use lexical parameters in reports to pass the query definition or just the where part of it.
Look at the reports online help for both of these solutions. -
I am having a strange problem with an update query I am running. Here are the specifics:
1. I run a script that extracts qualifying rows form a source table (S1), performs some calculation,s and stores the results in a temporary table (T1).
2. The calculations stored in the temporary table (T1) are only for a subset of rows in the source table (S1).
3. The temporary table (T1) uses the same primary key values as the source table (T1).
4. Once the calculations are completed, I want to update a single column on the source table (S1.CalcValue) with the calculated value from the temporary table (T1.CalcValue).
The problem is that I am doing monthly updates so I run month 1, do some verification of the data and then update the source table. Then repeat the process for months 2 through n. When I run the update for the month 2 data, the prior month 1 data for the column is lost. Below is the update script which looks like it should work and only update on the matching keys between the temporary table (T1) and the source table (S1). I was wondering if anyone could let me know what is wrong with this script and why.
I am new to Oracle having worked extensively in SQL Server, so the syntax differences are killing me right now so any help would be appreciated.
Update script:
procedure update_rvu AS
BEGIN
--update the test.RVU table
update test.RVU S1
set S1.CalcRVU = ( select
T1.CalcRVU
from
TMP_RVU T1
where
S1.GroupId = T1.GroupId
and
S1.PatientId = T1.PatientId
and
S1.InvoiceId = T1.InvoiceId
and
S1.TransId = T1.TransId
commit;
END update_rvu;
Edited by: user9009311 on Apr 14, 2010 4:47 PMMost likely you want a WHERE clause in your update portion ... something like
update test.RVU S1
set S1.CalcRVU = ( select
T1.CalcRVU
from
TMP_RVU T1
where
S1.GroupId = T1.GroupId
and
S1.PatientId = T1.PatientId
and
S1.InvoiceId = T1.InvoiceId
and
S1.TransId = T1.TransId
where exists
select null
from tmp_rvu t11
where S1.GroupId = T11.GroupId
and S1.PatientId = T11.PatientId
and S1.InvoiceId = T11.InvoiceId
and S1.TransId = T11.TransId
)You can also look into using the MERGE command (if you're on version 10 or better you can perform update only operations with it). I personally find it more 'friendly' than correlated updates a lot of the time. -
Help with Update query including JOIN
Hi,
This is my first post to this forum and really hoping someone is able to help me write an update query.
Here is my data model:
Table (Columns)
Services (ServiceCode, BranchID, GLCodeGUID)
GLCodes (GLCodeGUID, BranchID, GLCode)
I have added valid GLCode data to the Services table for BranchID = 99
I would like to update all other branch records in the service table to their corresponding GLCodeGUID values matched by GLCode.
This is the query I have come up with so far which is incorrect.
UPDATE S
SET S.GLAccountCodeGUID = G.GLCodeGUID
FROM Services S
JOIN GLCodes G
ON G.GLCodeGUID = S.GLAccountCodeGUID
JOIN Services SM
ON S.ServiceCode = SM.ServiceCode and SM.BranchID = 99
WHERE S.BranchID != 99
AND S.IsActive = 1
ORDER BY S.ServiceCodeReceived some assistance from a work colleague and solved this with the following Query:
UPDATE s2 SET s2.GLAccountCodeGUID = gl2.GLCodeGUID
FROM Services s1
JOIN GLCodes gl1
ON s1.GLAccountCodeGUID = gl1.GLCodeGUID
JOIN GLCodes gl2
ON gl1.GeneralLedgerCode = gl2.GeneralLedgerCode AND gl1.BranchID <> gl2.BranchID
JOIN Services s2
ON s1.ServiceCode = s2.ServiceCode AND s1.ServiceCode = s2.ServiceCode AND s1.BranchID <> s2.BranchID
WHERE s1.BranchID = 99 AND gl1.BranchID = 99 AND
s2.BranchID = 2 AND gl2.BranchID = 2 -
Hi all,
I have a simple update query problem. I have four tables
activist(activist_id,first_name,last_name,c_state),
membership(activist_id,g_n_id),
group_network(g_n_id,g_n_type_id),
school_grop_det(g_n_id,state). For some records in activist table the c_state column is null, i want to update that column with state column of school_group_det table.
Here is the query for the states which are null
select distinct a.activist_id,a.first_name,a.last_name,
a.c_state,sd.state from activist a,membership m,
group_network g,school_group_det sd where
a.activist_id=m.activist_id and g.g_n_id=m.g_n_id and
g.g_n_id=sd.g_N_id and a.c_state is null and g.g_n_type_id='1001'
order by a.activist_id
I got the activist_id,first_name,last_name,c_state from activist and state from school_group_det. now i as i told you want to update the c_state with state column of school_group_Det table.
Pleae any one help me
Thanks
SrinivasHi all,
I have a simple update query problem. I have four tables
activist(activist_id,first_name,last_name,c_state),
membership(activist_id,g_n_id),
group_network(g_n_id,g_n_type_id),
school_grop_det(g_n_id,state). For some records in activist table the c_state column is null, i want to update that column with state column of school_group_det table.
Here is the query for the states which are null
select distinct a.activist_id,a.first_name,a.last_name,
a.c_state,sd.state from activist a,membership m,
group_network g,school_group_det sd where
a.activist_id=m.activist_id and g.g_n_id=m.g_n_id and
g.g_n_id=sd.g_N_id and a.c_state is null and g.g_n_type_id='1001'
order by a.activist_id
I got the activist_id,first_name,last_name,c_state from activist and state from school_group_det. now i as i told you want to update the c_state with state column of school_group_Det table.
Pleae any one help me
Thanks
Srinivas -
Very urgent help - for update field1 nowait across databaselink
Hi,
We have a form that uses select for update field1 nowait for a table that is accessed across a database link. When we try to do this the form errors out giving frm-92101 error. If I comment out the for update statement then it works fine. I know it the for update that is causing the problem but I'm not sure how to fix it. Can someone help me please. Very urgent, we are in the middle of upgrade and we found this issue while testing the forms.
Any ideas or suggestions ?
I'm using 10g App.Server and 10g database.
Please help.
Thanks in advance.under which trigger you ran that update ?
-
Hi All....
Required help for one more query.
I have a table with data like this:
Cust_id Transaction_no
111 1
111 2
111 3
111 4
111 5
111 6
222 7
222 8
333 9
333 10
333 11
333 12
I wrote the following query :
select cust_id, ntile(3) over (order by cust_id) "Bucket" from trans_detls
The output is like this :
Cust_id Bucket
111 1
111 1
111 1
111 1
111 2
111 2
222 2
222 2
333 3
333 3
333 3
333 3
The problem is that I dont want the cust_id to overlap in buckets. That is one cust_id should be present in only one bucket.
Is this possible?
Thanks in advance.
AmeyaOr Something like..
SQL> select * from test;
ID NO
111 1
111 2
111 3
111 4
111 5
111 6
222 7
222 8
333 9
333 10
333 11
333 12
12 rows selected.
SQL> select id, ntile(3) over (order by rn) "Bucket"
2 from(
3 select id,row_number() over(partition by id order by no) rn
4 from test);
ID Bucket
111 1
222 1
333 1
111 1
222 2
333 2
111 2
333 2
111 3
333 3
111 3
111 3
12 rows selected. -
Hi, I want to update status_code of table_2. T_ID is the primary key in both table (Table_1 and table_2). The condition is any person's age >70 then status_code should be 'R' and if person's age<70 then status_code should be 'N'. Please help on this
Update query.
/*Table_1*/
T_ID LASTNAME FIRSTNAME DOB
1001 KAISER SUJIR 01/01/1942
1002 SMITH HUJR 01/01/1948
1003 JOHN JANE 02/01/1958
/*Table_2*/
T_ID LASTNAME FIRSTNAME STATUS_CODE
1001 KAISER SUJIR R
1002 SMITH HUJR R
1003 JOHN JANE R
/*Need the Following Result after the Update*/
T_ID LASTNAME FIRSTNAME STATUS_CODE
1001 KAISER SUJIR R --The Age is >70 that's why status_code is 'R'
1002 SMITH HUJR N --The Age is <70
1003 JOHN JANE N --The Age is <70DECLARE @table1 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), dob DATE)
INSERT INTO @table1 (T_ID, lastName, firstName, dob) VALUES (1001, 'KAISER', 'SUJIR' ,'01/01/1942'),(1002, 'SMITH', 'HUJR', '01/01/1948'),(1003, 'JOHN', 'JANE', '02/01/1958'),(1004, 'Jack', 'Jackson', '12/03/1944')
DECLARE @table2 TABLE (T_ID INT, lastName VARCHAR(30), firstName VARCHAR(30), statusCode CHAR(1))
INSERT INTO @table2 (T_ID, lastName, firstName, statusCode) VALUES (1001, 'KAISER', 'SUJIR', 'R'),(1002, 'SMITH', 'HUJR', 'R'),(1003, 'JOHN', 'JANE', 'R'),(1004, 'Jack', 'Jackson', 'R')
-- tables set up
UPDATE @table2
SET statusCode = CASE WHEN DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END >= 70 THEN 'R' ELSE 'N' END
FROM @table2 t2
INNER JOIN @table1 t1
ON t2.T_ID = t1.T_ID
SELECT *, DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP) - CASE WHEN DATEADD(YEAR,DATEDIFF(YEAR,t1.dob,CURRENT_TIMESTAMP),t1.dob) > CURRENT_TIMESTAMP THEN 1 ELSE 0 END
FROM @table2 t2
INNER JOIN @table1 t1
ON t2.T_ID = t1.T_ID -
For Update Query with Wait Clause from ORACLE Forms
Hi
We are using Oracle Forms 10g running with 10g database 10.2.0.1.0. We happend to see a query which is getting generated in AWR report like Select rowid, all_columns from TableName for Update of C1 Nowait. But no such query is really written in forms and we are aware that, Any query prefixed with rowid is definitely executing from Forms. But how the ForUpdate and Nowait clause is appended to the query.
We have checked the following properties in the database Block
*1) Locking Mode is set to Automatic*
*2) Update Changed Columns only is set to YES*
*3) Query all records is set to No (Though this particular property may not be relevant to the issue)*
What is the property or setting which might trigger such a query from ORACLE Forms with ForUpdate and Nowait clause.
Any ideas/suggestions on why such behaviour. Please have a healthy discussion on this. Thanks in advance.Why have you started another thread on the same thing?
FOR UPDATE cursor is causing Blocking/ Dead Locking issues
Just use one thread to avoid confusion.
The fact that nobody has answered on the other thread for a couple of days could be to do with it being the weekend and most people are not at work.
Either be patient or, if it's more "urgent" than that, raise a SR/Tar with Oracle metalink. -
with :
resultset = stmt.executeQuery("select nxtid from mytable .. for update");
I have the ora-1002 Erreur.
Could you help me.
null<BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by burgniar:
with :
resultset = stmt.executeQuery("select nxtid from mytable .. for update");
I have the ora-1002 Erreur.
Could you help me.<HR></BLOCKQUOTE>
Solution is :
conn.setAutoCommit(false);
null -
Help for a query to add columns
Hi,
I need for a query where I should add each TableC value as an additional column.
Please suggest...
I have 3 tables (TableA, TableB, TableC). TableB stores TableA Id and TableC stores TableB Id
Considering Id of TableA.
Sample data
TableA :
ID NAME TABLENAME ETYPE
23 Name1 TABLE NAMEA Etype A
TableB :
ID A_ID RTYPE RNAME
26 23 RTYPEA RNAMEA
61 23 RTYPEB RNAMEB
TableC :
ID B_ID COMPNAME CONC
83 26 Comp Name AA 1.5
46 26 Comp Name BB 2.2
101 61 Comp Name CC 4.2
Scenario 1: AS PER ABOVE SAMPLE DATA Put each TableC value as an additional column.
For an Id in TableA(23) where TableB contains 2 records of A_ID (26, 61) and TableC contains 2 records for 26 and 1 record for 61.
Output required: Put each TABLEC value as an additional column
TableA.NAME TableA.ETYPE TableB.RTYPE TableC_1_COMPNAME TableC_1_CONC TableC_2_COMPNAME TableC_2_CONC
Name1 EtypeA RTypeA Comp Name AA 1.5 Comp Name BB 2.2 so on..
Name1 EtypeA RTypeB Comp Name CC 4.2 NULL NULL
Scenario 2: If Table C contains ONLY 1 row for each Id in TableB, output should be somewhat
Output:
TableA.NAME TableA.ETYPE TableB.RTYPE TableC_1_COMPNAME
TableC_1_CONCvalue value value value valueHi,
Welcome to the forum!
Do you want the data from TableC presented
(1) in one column, or
(2) in several columns (a different column of results for each row in the original TableC)?
(1) Is called String Aggregation and is easier than (2).
The best way to do this is with a user-defined aggregate function (STRAGG) which you can copy from asktom.
Ignoring TableA for now, you could get what you want by saying
SELECT b.rtype
, STRAGG ( c.compname
|| ' '
|| c.conc
) AS c_data
FROM TableB b
JOIN TableC c ON b.id = c.b_id
GROUP BY b.rtype;(2) Presenting N rows of TableC as it they were N columns of the same row is called a pivot. Search for "pivot" or "rows to columns" to find examples of how to do this.
The number of columns in a result set is hard-coded into the query. If you don't know ahead of time how many rows in TableC will match a row in TableB, you can:
(a) guess high (for example, hard-code 20 columns and let the ones that never contain a match be NULL) or,
(b) use Dynamic SQL to write a query for you, which has exactly as many columns as you need.
The two scripts below contain basic information on pivots.
This first script is similar to what you would do for case (a):
-- How to Pivot a Result Set (Display Rows as Columns)
-- For Oracle 10, and earlier
-- Actually, this works in any version of Oracle, but the
-- "SELECT ... PIVOT" feature introduced in Oracle 11
-- is better. (See Query 2, below.)
-- This example uses the scott.emp table.
-- Given a query that produces three rows for every department,
-- how can we show the same data in a query that has one row
-- per department, and three separate columns?
-- For example, the query below counts the number of employess
-- in each departent that have one of three given jobs:
PROMPT ========== 0. Simple COUNT ... GROUP BY ==========
SELECT deptno
, job
, COUNT (*) AS cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno
, job;
Output:
DEPTNO JOB CNT
20 CLERK 2
20 MANAGER 1
30 CLERK 1
30 MANAGER 1
10 CLERK 1
10 MANAGER 1
20 ANALYST 2
PROMPT ========== 1. Pivot ==========
SELECT deptno
, COUNT (CASE WHEN job = 'ANALYST' THEN 1 END) AS analyst_cnt
, COUNT (CASE WHEN job = 'CLERK' THEN 1 END) AS clerk_cnt
, COUNT (CASE WHEN job = 'MANAGER' THEN 1 END) AS manager_cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno;
-- Output:
DEPTNO ANALYST_CNT CLERK_CNT MANAGER_CNT
30 0 1 1
20 2 2 1
10 0 1 1
-- Explanation
(1) Decide what you want the output to look like.
(E.g. "I want a row for each department,
and columns for deptno, analyst_cnt, clerk_cnt and manager_cnt)
(2) Get a result set where every row identifies which row
and which column of the output will be affected.
In the example above, deptno identifies the row, and
job identifies the column.
Both deptno and job happened to be in the original table.
That is not always the case; sometimes you have to
compute new columns based on the original data.
(3) Use aggregate functions and CASE (or DECODE) to produce
the pivoted columns.
The CASE statement will pick
only the rows of raw data that belong in the column.
If each cell in the output corresponds to (at most)
one row of input, then you can use MIN or MAX as the
aggregate function.
If many rows of input can be reflected in a single cell
of output, then use SUM, COUNT, AVG, STRAGG, or some other
aggregate function.
GROUP BY the column that identifies rows.
PROMPT ========== 2. Oracle 11 PIVOT ==========
WITH e AS
( -- Begin sub-query e to SELECT columns for PIVOT
SELECT deptno
, job
FROM scott.emp
) -- End sub-query e to SELECT columns for PIVOT
SELECT *
FROM e
PIVOT ( COUNT (*)
FOR job IN ( 'ANALYST' AS analyst
, 'CLERK' AS clerk
, 'MANAGER' AS manager
NOTES ON ORACLE 11 PIVOT:
(1) You must use a sub-query to select the raw columns.
An in-line view (not shown) is an example of a sub-query.
(2) GROUP BY is implied for all columns not in the PIVOT clause.
(3) Column aliases are optional.
If "AS analyst" is omitted above, the column will be called 'ANALYST' (single-quotes included).
{code}
The second script, below, shows one way of doing a dynamic pivot in SQL*Plus:
{code}
How to Pivot a Table with a Dynamic Number of Columns
This works in any version of Oracle
The "SELECT ... PIVOT" feature introduced in Oracle 11
is much better for producing XML output.
Say you want to make a cross-tab output of
the scott.emp table.
Each row will represent a department.
There will be a separate column for each job.
Each cell will contain the number of employees in
a specific department having a specific job.
The exact same solution must work with any number
of departments and columns.
(Within reason: there's no guarantee this will work if you
want 2000 columns.)
Case 0 "Basic Pivot" shows how you might hard-code three
job types, which is exactly what you DON'T want to do.
Case 1 "Dynamic Pivot" shows how get the right results
dynamically, using SQL*Plus.
(This can be easily adapted to PL/SQL or other tools.)
PROMPT ========== 0. Basic Pivot ==========
SELECT deptno
, COUNT (CASE WHEN job = 'ANALYST' THEN 1 END) AS analyst_cnt
, COUNT (CASE WHEN job = 'CLERK' THEN 1 END) AS clerk_cnt
, COUNT (CASE WHEN job = 'MANAGER' THEN 1 END) AS manager_cnt
FROM scott.emp
WHERE job IN ('ANALYST', 'CLERK', 'MANAGER')
GROUP BY deptno
ORDER BY deptno
PROMPT ========== 1. Dynamic Pivot ==========
-- ***** Start of dynamic_pivot.sql *****
-- Suppress SQL*Plus features that interfere with raw output
SET FEEDBACK OFF
SET PAGESIZE 0
SPOOL p:\sql\cookbook\dynamic_pivot_subscript.sql
SELECT DISTINCT
', COUNT (CASE WHEN job = '''
|| job
|| ''' ' AS txt1
, 'THEN 1 END) AS '
|| job
|| '_CNT' AS txt2
FROM scott.emp
ORDER BY txt1;
SPOOL OFF
-- Restore SQL*Plus features suppressed earlier
SET FEEDBACK ON
SET PAGESIZE 50
SPOOL p:\sql\cookbook\dynamic_pivot.lst
SELECT deptno
@@dynamic_pivot_subscript
FROM scott.emp
GROUP BY deptno
ORDER BY deptno
SPOOL OFF
-- ***** End of dynamic_pivot.sql *****
EXPLANATION:
The basic pivot assumes you know the number of distinct jobs,
and the name of each one. If you do, then writing a pivot query
is simply a matter of writing the correct number of ", COUNT ... AS ..."\
lines, with the name entered in two places on each one. That is easily
done by a preliminary query, which uses SPOOL to write a sub-script
(called dynamic_pivot_subscript.sql in this example).
The main script invokes this sub-script at the proper point.
In practice, .SQL scripts usually contain one or more complete
statements, but there's nothing that says they have to.
This one contains just a fragment from the middle of a SELECT statement.
Before creating the sub-script, turn off SQL*Plus features that are
designed to help humans read the output (such as headings and
feedback messages like "7 rows selected.", since we do not want these
to appear in the sub-script.
Turn these features on again before running the main query.
{code}
Maybe you are looking for
-
Batch to Batch Transfer and Tracking
Question, Since Batch to batch material transfer is possible using SAP standard functionality. On my floor, the raw material i am consuming is batch managed and causing accounts error and negative stock due to wrong batch no. posting at the time of C
-
Any way to share MacBook Air's external SuperDrive with PC?
Not really sure if this is the right spot to put this question but I couldn't really think of a better one. Here's my problem: I've got a PC which I need to run the backup disc creator on. Unfortunately, the optical drive on my PC doesn't work. My qu
-
how can i see Un-invoiced GR Report? Moderator message: Locked. Reason: basic question. Points will be removed. Edited by: Csaba Szommer on Feb 13, 2012 8:21 AM
-
I encountered ABAP runtime error when generating this report for 2 days. So, yesterday I run this report on background. Most of the info was missing in the report when I double check it with FS10N. Pls refer to the attached report. Those highlighted
-
Why a site that has follow content disable can be follow from my site
Hi, this is my question. I have a site where Follow Content feature is deactivated, so, the follow icon doesn't appear. Now, If I search the site from MySite, I can find the site, click on the elipsis and click on Follow, so, if the site has this fea