Help on query: how to produce from columns of ranks?
Hi allI have a table table1 with below the structure and data
Item State Value
A1 MS 100
A1 GOA 3
A1 UP 4
B2 MS 34
B2 GOA 55
B2 PB 3
B2 DL 4
B3 MS 99
B3 TN 1
I have a requirement to query this table and generate the output belowItem MS GOA UP PB DL TN
A1 100 3 4 0 0 0
B2 34 55 0 3 4 0
B3 99 0 0 0 0 1
The problem here is that we can have multiple status codes, so as a result the query should return dynamically the number of columnsIs it possible to produce above output? Any help will be appreciated.
Oracle DB Version - Oracle 8i
Thanks in advance!
Hello
This is called a pivot .
The basic technique is something like:
SELECT item
, SUM (CASE WHEN state = 'MS' THEN value ELSE 0) AS ms
, SUM (CASE WHEN state = 'GOA' THEN value ELSE 0) AS goa
, SUM (CASE WHEN state = 'UP' THEN value ELSE 0) AS up
, SUM (CASE WHEN state = 'PB' THEN value ELSE 0) AS pb
, SUM (CASE WHEN state = 'DL' THEN value ELSE 0) AS dl
, SUM (CASE WHEN state = 'TN' THEN value ELSE 0) AS tn
FROM table_x
GROUP BY item;
but this requires you to know indicates how many there are, and what they are, when you write the query.
Since you have not, you must run a preliminary motion that will generate a select like the one above, or at least SUM expressions for variable columns. This is called dynamic SQL code , and a technique to do this is included below. (The example uses COUNT, but any aggregate, including the SUM function, work).
Another possibility is the aggregation of the chain, where instead of individual columns for each State, you have a huge column VARCHAR2, formatted to look like separate columns. The avaiable tools to do this in Oracle 8.1 are quite poor, however, so I think you're better with dynamic SQL.
/*
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.)
NOTE: Using SQL*Plus file I/O, as in this example, is just
one of many ways to do dynamic SQL.
*/
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.
*/
Tags: Database
Similar Questions
-
Help - Tuning query based on the status column
Hello
I have a query in which I need to fetch records based on values in the status column. It can contain the values 'A' and 'P '. A record can have an "A" record and a record of 'P '. My conditions are,
(1) when it is only 'A' record, can return 'A' record.
(2) for the 'A' and 'P' folder is there, then return 'A' record.
(3) when 'P' registration is only, then return 'P' registration.
There are about 3 records 'A' Lake and 3K 'P '. I tried to use 'by' clause queries, but performance are too bad and I am not able to use it. When running as independent queries 'A' retrieval of documents is faster compared to the records of 'P '. When running in 'by' clause of the query is suspended. Please can anyone help how can be managed?
Due to restrictions, I won't be able to view the actual code. I post here a sample.
Example code:
Thank youWITH q1 AS (SELECT * FROM tab WHERE status = 'A'), q2 AS (SELECT * FROM tab WHERE status = 'P'), q3 AS (SELECT * FROM q1 UNION ALL (SELECT * FROM q2 WHERE NOT EXISTS (SELECT 1 FROM q1))) SELECT * FROM q3 WHERE ROWNUM < 501;
KadochOne way is to use analytics like this:
SELECT * FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY
ORDER BY t.status) rn FROM tab t WHERE t.status IN ('A', 'P')) WHERE rn = 1 John
-
How to remove a column from a table in a dell identtiymananger 7.0
How to remove a column from a table in a dell identtiymananger 7.0
Hello
In Version 7 of the removal of a single custom column can be accomplished by a stored procedure, available in the database called: QBM_PColumnDrop
Hope that helps.
Cordially Fatih
-
Hi, I, m need Adobe Photoshop CC 2015 offline trial version Installer. Please help me. How to download the version from the adobe web site offline?
First read the important instructions on this page.
-
How to access a column value in a Select list in a tabular presentation for each line
Hello
Environment: Using Oracle APEX v4.2.1 on an Oracle 11 g 2 DB
In a tabular presentation using the following example query, i.e.:
select "EMPNO", "EMPNO" EMPNO_DISPLAY, "ENAME", "HIREDATE", "SAL", "DEPTNO", "MY_LOV" from"#OWNER#"."EMP"
I need access to every line of my sub form of table, the EMPNO of this line value, within a list of selection (query based LOV) in the column "MY_LOV."
So, basically, the MY_LOV column in my table presentation, would be a list of selection (query based LOV) where MY_EMPNO =: EMPNO (first column in the select statement above), for each line of the tabular presentation.
With the help of a picture ( Tom's Blog ) and assuming 'Deptno' column here is actually my new column, i.e. "MY_LOV, I want to know how this list of selection based on lov query would be able to access each EMPNO down in the form of tables, i.e. 7839, 7698, 7782 etc.?
Any help would be appreciated.
Thank you.
Tony.
Hi Tony,.
Take a look at the API APEX_ITEM for LOV
http://docs.Oracle.com/CD/E37097_01/doc/doc.42/e35127/apex_item.htm#AEAPI208
Kind regards
Brad
-
Query the filter on the column
Query the filter on the column
Business activity IN the Transactions of AR OBIA
the fact is filtered on (RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = 'REV' OR RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = "UNEARN") in the Informatica ETL
(RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = 'REV' OR RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = "UNEARN")I need to provide tax information within the area of topic in the table above and extend the filter to include the "tax".
(RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = 'REV' OR RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = "UNEARN")
and
(RA_CUST_TRX_LINE_GL_DIST_ALL. ACCOUNT_CLASS = 'TAX') - which comes from Account_classThis change affects the existing domain and in turn produce a greater number report
Second
If I want to understand how I try and work on the report
AR amount divided by tax
The class number account amount AR invoice
001 REV 100
001 tax 20
the report above, I have to remove the filter on the ETL
but to ensure that when the user account IS NOT reached the class column in the analysis then by default put a filter on the source column in fact that maintains only "REV" or "UNEARN".Thank you
The answer lies in space analysis of revenues GL object
-
Hello
I have a ColumnContainer that looks like the following (from the example of chassis)
< com.vmware.ui.lists.ColumnContainer >
< uid > < / uid >
< dataInfo >
< com.vmware.ui.lists.ColumnDataSourceInfo >
<!-table of the properties of the subject of this column, usually one->
< requestedProperties >
< string > name < / String >
< / requestedProperties >
<!--use sortProperty to allow the column to sort on header click-->
< Proprietetri > name < / sortProperty >
<! - exportProperty of use to export data from column - >
< exportProperty > name < / exportProperty >
< /com.vmware.ui.lists.ColumnDataSourceInfo >
< / dataInfo >
< item >
< mx.controls.advancedDataGridClasses.AdvancedDataGridColumn >
< headerText > #{name} < / headerText >
<!--dataField must match a property requested, its text value will be inserted-->
< dataField > name < / dataField >
< /mx.controls.advancedDataGridClasses.AdvancedDataGridColumn >
< / component >
< /com.vmware.ui.lists.ColumnContainer >
The cell needs display an icon and text side by side. How to make an image in the cell? Outside the environment of plugin, I was able to successfully create an AdvancedDataGrid with a custom "itemRenderer"? Unfortunately, I'm not able to do the same thing here and do appear correctly on the screen. I was wondering how I can associate the AdvancedDataGridColumn with an itemRenderer?
Any help is appreciated.
Thank you
Shankar
There must be something wrong with your code. The best way to get help for this sort of thing is to modify one of our samples to reproduce the problem so that we can reproduce it and focus on the thing that it does not.
BTW, in version 5.5 the com.vmware.ui.lists.ColumnSetContainer API is still supported but has been deprecated, we recommend that you set the extensibility of the column directly in plugin.xml such as shown in samples of chassis-app 5.5 (you don't need all component Flex, but cannot display text). This is to ensure compatibility with future major version.
-
How to list the columns for a view
Dear experts
I know how to list the columns in a table. This easy by querying the data USER_TAB_COLUMNS dictionary.
But my problem is how to issue a query that returns the columns for a view?
Thanks in advance
USER_TAB_COLUMNS stores the metadata for both views.
Select * from user_tab_columns where table_name = 'YOUR_VIEW_NAME"of order of column_id. -Replace with your view_name (mandatory course)
See you soon,.
Manik.
-
Oracle how to multiply two columns of different tables and results
Oracle how to multiply two columns of different tables and get the result in the third column?
I want to multiply all the lines of the quantinty column in the table of quantity with the relevant lines of the table of prices price column and get the result of multiplying in the third column. What should I use procedure trigerr? OR IS IT POSSIBLE HOW TO DO IT PLEASE HELP :D
Edited by: 994229 2013-03-15 12:44/* Formatted on 3/15/2013 3:51:08 PM (QP5 v5.185.11230.41888) */ CREATE TABLE mytable1 AS (SELECT 1 id, 5 VALUE FROM DUAL UNION ALL SELECT 2, 7 FROM DUAL UNION ALL SELECT 3, 8 FROM DUAL); CREATE TABLE mytable2 AS (SELECT 1 id, 4 VALUE FROM DUAL UNION ALL SELECT 2, 12 FROM DUAL UNION ALL SELECT 10, 12 FROM DUAL); SELECT id, mytable1.VALUE, mytable2.VALUE, mytable1.VALUE * mytable2.VALUE product FROM mytable1 FULL OUTER JOIN mytable2 USING (id) ORDER BY id;
ID VALUE VALUE_1 PRODUCT 1 5 4 20 2 7 12 84 3 8 10 12
-
Need help for query flat_file type clobdata oracle table data.
Hi Sir,
I need help to query oracle table flat file data having given clob type.
COLUMN FOR CHAR_DATA FLAT_FILEOracle Version: Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product PL/SQL Release 10.2.0.1.0 - Production "CORE 10.2.0.1.0 Production" TNS for 32-bit Windows: Version 10.2.0.1.0 - Production NLSRTL Version 10.2.0.1.0 - Production Source table CREATE TABLE order_details ( QUEUE_SEQNUM NUMBER(10,0) NOT NULL ENABLE, LINE_SEQNUM NUMBER(10,0) NOT NULL ENABLE, CHAR_DATA CLOB, OPTIMISTIC_LOCK_KEY NUMBER(20,0) )
EXPECTED RESULTS:EU,6067AT,AT10,000000402004,NexiumGERDManagementProject,Z435,,ZZ29,NIS-GOLD,AT EU,6067AT,AT10,000000402038,NIS-OEU-ARI-2007/1,Z450,,ZZ29,NIS-OEU-ARI-2007/1,AT EU,6067AT,AT10,000000402039,SymbicortNISinCOPD,Z450,,ZZ29,NIS-REU-DUM-2007/1,AT EU,6067AT,AT10,000000402040,D1443L00044SeroquelXRRuby,Z450,,ZZ29,D1443L00044,AT EU,6067AT,AT10,000000402041,NIS-GEU-DUM-2008/1,Z450,,ZZ29,NIS-GEU-DUM-2008/1,AT EU,6067AT,AT10,000000402042,SonstigeAktivitätenLCM,Z450,,ZZ29,.,AT EU,6067AT,AT10,000000402134,D1680L00002Saxagliptin,Z450,,ZZ29,D1680L00002,AT EU,6067AT,AT10,000000402199,SeroquelWaveNIS,Z450,,ZZ29,NIS-NEU-DUM-2009/1,AT EU,6067AT,AT10,000000402313,SeroquelExtra(D1443L00082),Z450,,ZZ29,D1443L00082,AT EU,6067AT,AT10,000000402517,AtlanticD5130L00006(AZD6140),Z450,,ZZ29,D5130L00006,AT EU,6067AT,AT10,000000554494,ArimidexSt.Gallen(13+2),Z142,,ZZ09,,AT EU,6067AT,AT10,000000554495,ArimidexASCO(5delegates),Z142,,ZZ09,,AT EU,6067AT,AT10,000000554496,ArimidexSanAntonio6delegates,Z142,,ZZ09,,AT EU,6067AT,AT10,000000554497,ArimidexBreastCancerSummit(13+2),Z130,,ZZ09,,AT EU,6067AT,AT10,000000554498,ArimidexEIH(15delegates),Z130,,ZZ09,,AT EU,6067AT,AT10,000000554499,ArimidexNIFA(200delegates),Z135,,ZZ09,,AT EU,6067AT,AT10,000000554500,ArimidexNIFAworkshops(8x25),Z135,,ZZ09,,AT EU,6067AT,AT10,000000554501,ArimidexPraktischeGyn.Fortbildung,Z147,,ZZ09,,AT EU,6067AT,AT10,000000554502,ArimidexAGO,Z147,,ZZ09,,AT EU,6067AT,AT10,000000554503,ArimidexHämato/OnkologieKongress,Z147,,ZZ09,,AT EU,6067AT,AT10,000000554504,ARIMIDEXGYNäKOLOGENKONGRESS,Z147,,ZZ09,,AT EU,6067AT,AT10,000000554505,ArimidexChirurgenkongress,Z147,,ZZ09,,AT
AFFIRM_CODE COMPANY_CODE INTERNAL_ORDER_CODE INTERNAL_ORDER_DESC ENIGMA_ACTIVITY SUB_ACTIVITY_CODE IN_AFF_IND ORDER_TYPE EXTERNAL_ORDER COUNTRY EU 6067AT AT10 000000402004 NEXIUMGERDMANAGEMENTPROJECT Z435 NULL ZZ29 NIS-GOLD AT EU 6068AT AT11 000000402005 NEXIUMGERDMANAGEMENTPROJECT Z435 NULL ZZ29 NIS-GOLD AT
Sorry, my bad. Without database at hand, I'll try 'baby steps' (borrowed from Frank) so you don't confuse it with errors that I might add (happens far too often already, but at least you won't "swallow" as forum members think is one of the main goals of this fighter - help her learn - providing not only the proverbial fish.)
Search the Forum - your problem is one of its best sellers. Watching {message identifier: = 10694602} ("split string into" was the key word used in research) you can try something asselect table_row, level clob_row, regexp_substr(char_data,'[^' || chr(13) || chr(10) || ']+',1,level) the_line from (select to_char(queue_seqnum)||':'||to_char(line_seqnum) table_row, char_data from order_details ) connect by regexp_substr(char_data,'[^' || chr(13) || chr(10) || ']+',1,level) is not null and prior char_data = char_data and prior table_row = table_row and prior sys_guid() is not null
to get all the s the_lineall CLOB and after that the use of the example even to get your columns of each the_line.
Concerning
Etbin
Edited by: Etbin on 3.2.2013 09:01
.. .but I m connected to do things according to the instructions, I can't do something.
Used to happen to me too and I did as told to the but only after explaining any disadvantages, I was aware of in time. The last sentence is usually: "O.K. now be just and Don't come back with that kind of thing when it turns out that this isn't the right thing."
rp0428 post - something to remember. -
How to add the column to the compressed table
Hi gurus,
Can someone help me how to add a column to compressed tables
Thanks in advanceThe only difference is if added column has a default value. In this case:
SQL> create table tbl(id number,val varchar2(10)) 2 / Table created. SQL> insert into tbl 2 select level,lpad('X',10,'X') 3 from dual 4 connect by level <= 100000 5 / 100000 rows created. SQL> select bytes 2 from user_segments 3 where segment_name = 'TBL' 4 / BYTES ---------- 3145728 SQL> alter table tbl move compress 2 / Table altered. SQL> select bytes 2 from user_segments 3 where segment_name = 'TBL' 4 / BYTES ---------- 2097152 SQL> alter table tbl add name varchar2(5) default 'NONE' 2 / alter table tbl add name varchar2(5) default 'NONE' * ERROR at line 1: ORA-39726: unsupported add/drop column operation on compressed tables SQL> alter table tbl add name varchar2(5) 2 / Table altered. SQL> update tbl set name = 'NONE' 2 / 100000 rows updated. SQL> commit 2 / Commit complete. SQL> select bytes 2 from user_segments 3 where segment_name = 'TBL' 4 / BYTES ---------- 7340032 SQL> select compression from user_tables where table_name = 'TBL' 2 / COMPRESS -------- ENABLED SQL> alter table tbl move compress 2 / Table altered. SQL> select bytes 2 from user_segments 3 where segment_name = 'TBL' 4 / BYTES ---------- 2097152 SQL>
SY.
-
-Create/insert example:
create table xxdummy)
integer ID,
name varchar2 (40),
Description varchar2 (100)
);
insert into xxdummy values (1, 'L', ' press L Simple');
insert into xxdummy values (2, 'XL', "XL with no film");
insert into xxdummy values (2, 'web', "XL with no film");
insert into xxdummy values (3, 'XL', 'XL with the Film');
insert into xxdummy values (3, 'Film', 'XL with the Film');
insert into xxdummy values (3, 'print', 'XL with the Film');
insert into xxdummy values (4, the of ', 'servo with the film');
insert into xxdummy values (4, 'Film', 'servo with the film');
insert into xxdummy values (5, the servo only ',' ');
insert into xxdummy values (6, 'L', 'Press L Simple');
insert into xxdummy values (7, 'XL', "XL with no film");
insert into xxdummy values (8, 'XL', 'XL with the Film');
insert into xxdummy values (8, 'Film', 'XL with the Film');
insert into xxdummy values (8, 'guide', 'XL with the Film');
-drop table xxdummy;
Select * from xxdummy;
SELECT id, description, decode type ("name, ' the, 'L only', 'XL', ' Got XLs here","no opinion")
of xxdummy
WHERE name in ('l', 'XL')
In above query for the type of column, I want to display 'Only L', "XL with Film", "XL without Film.
How can I do this?
Thank youHello
You can change the Andreas solution' to show the name instead of the description and some minor changes in the wording of the type.
You can also rearrange the expression BOX so that you do not need a nested case.select id, name, CASE WHEN name = 'L' THEN ' L Only' WHEN name != 'XL' THEN 'dont know' WHEN INSTR (description, 'with no') >0 THEN 'XL No Film' ELSE 'XL Film' END type from xxdummy where name in ('L','XL' ) ;
-
How to boot from a USB - Portege R500 flash drive
Hello
I have a Portege R500 running Windows XP, presented about 2 years ago and recently contracted a virus that has infected some of the startup files as the minute I connect it disconnects again, even in SafeMode! The quickest way I can think sorting is to reformat with the XP Recovery disk and reinstall windows.
Problem! The CD/DVD drive on the computer laptop stopped working earlier, tried almost everything in the thread on this site, but had no luck.
So my plan was to boot from a USB flash drive and do it this way. However in the boot parameters I only have the options of HARD drive / floppy drive / CD-ROM / LAN, none of them work. Does anyone know how to boot from USB flash drives?
Any help would be really appreciated
Hello
As far as I know, it should be possible to boot from USB FDD
I don't know if you would be able to boot from a USB flash drive, but it of certainly worth a try m
Generally, you can try to press the F12 key when the laptop is turned on.
A start menu should appear on the screen, then you should see all bootable devices.PS: as far as I know the USB startup was available in ToshibaHWSetup (tool of Toshiba which changes the settings of the BIOS under windows OS.) So I guess boot from USB must be possible.
Welcome them
-
Qosmio G35-AV600: I don't know how to boot from a CD - R
I'm having the problem of 'Bad Machine' and I downloaded the utility DMI.
I don't know how to boot from a CD - R. I don't have a floppy drive. Help me Toshiba.In fact, I burned the .iso to a CD image file and kept pressed 'c', while starting my computer was. I did not work.
-
Could someone help me that how can I save 100 to 200 in labview at equal distance from the values of a particular number? Lets assume that I have a number of 50 and I need 100-200 equidistant values between 0 and 50. I made a sample program, but it gives error of memory storage that I did not understand how to solve...
You make the mistake to make equal comparisons on numbers floating point. It's very dangerous. Most likely, your VI will never stop until the computer is out of memory. Replace the 'equal' by ' greater than or equal to "and you should be OK.
As you know the number of iterations in advance, you must use a loop FOR, see how far you get. In addition, your shift register must probably be initialized.
(Of course, it is also 'ramp model' If you want a canned solution. )
Maybe you are looking for
-
T500 operating at maximum speed
My t500 runs at full speed or a little more at 2926 mhz acording to AIDA64 while on battery. This makes the laptop run hot and battery life. I have reset the BIOs to maximize independence and then set as default. I even removed the battery cmos for a
-
am not able to use the keyboard Finns characters.how special use these special characters
We bought a new acer laptop specifications of the laptop are as mentioned below > ACER ASPIRE S3 13.3 INCHES We are not able to understand how to enter some special characters using the key board, some characters are shown below a o a Could you p
-
More for Windows xp is compatible with vista?
-
Reference Dell 946 AIO windows 7 64 bit, after installing AIOC.exe has stopped working
I was extremely upset with this problem and it seems that there are tons of discussions but none of the solutions work for me. I have a Dell AIO 946. Windows 7 64-BIT fully updated I installed win 7 64 driver (5 or 6 times now) Prints perfectly fine,
-
People hear my helmet through my output sounds
So I've been struggling with this for a while now and I can't seem to find an answer to this anywhere. The problem is when I use my mic to speak to the people via Skype/ventrilo/teamspeak anything really (problem also occurs when you are recording in