[Oracle 8i] Query for N rows by column value?
I was just wondering if what I want to do is possible within my query (rather than programmatically)...
I want to return the N most recent records for each unique value in a particular column.
Here's a sample table:
CREATE TABLE orders
( order_no numeric(10)
part_no varchar(5)
close_date date
order_qty numeric(10)
scrap_qty numeric(10)
CONSTRAINT order_pk PRIMARY KEY (order_no)
);And some sample data....
INSERT INTO orders VALUES
(0000012345,'ABC-1',TO_DATE('01-01-2010','mm-dd-yyyy'),10,1);
INSERT INTO orders VALUES
(0000013498,'ABC-1',TO_DATE('01-05-2010','mm-dd-yyyy'),12,2);
INSERT INTO orders VALUES
(0000033452,'ABC-1',TO_DATE('01-10-2010','mm-dd-yyyy'),5,0);
INSERT INTO orders VALUES
(0000001468,'ABC-1',TO_DATE('01-15-2010','mm-dd-yyyy'),15,1);
INSERT INTO orders VALUES
(0000022349,'BR723',TO_DATE('01-03-2010','mm-dd-yyyy'),8,1);
INSERT INTO orders VALUES
(0000069581,'BR723',TO_DATE('01-05-2010','mm-dd-yyyy'),5,0);
INSERT INTO orders VALUES
(0000436721,'BR723',TO_DATE('01-10-2010','mm-dd-yyyy'),14,1);
INSERT INTO orders VALUES
(0000213446,'A5001',TO_DATE('01-06-2010','mm-dd-yyyy'),5,1);
INSERT INTO orders VALUES
(0000327987,'A5001',TO_DATE('01-08-2010','mm-dd-yyyy'),5,0);
INSERT INTO orders VALUES
(0000041353,'A5001',TO_DATE('01-14-2010','mm-dd-yyyy'),12,1);
INSERT INTO orders VALUES
(0000011241,'A5001',TO_DATE('01-15-2010','mm-dd-yyyy'),5,1);In this example, what I want to return are the 2 most recent orders (by close_date) for each part number.
Here is a table with the results I want to get, based on the scenario above:
order_no part_no close_date order_qty scrap_qty
0000001468 'ABC-1' '01-15-2010' 15 1
0000033452 'ABC-1' '01-10-2010' 5 0
0000436721 'BR723' '01-10-2010' 14 1
0000069581 'BR723' '01-05-2010' 5 0
0000011241 'A5001' '01-15-2010' 5 1
0000041353 'A5001' '01-14-2010' 12 1Is it possible to write a query to get these results, or am I going to have to query for all available data, and find the 2 most recent rows programmatically?
Thanks in advance!
Hi,
user11033437 wrote:
I'm going to test that out right now. I think if it works, I may need to use dense_rank() rather than rank(), because it is possible that two orders for the same part number could have the same close date, and according to what I've looked up on the rank() and dense_rank() functions, rank() can give non-consecutive results if the values are the same.What's wrong with non-consecutive values?
Use RANK, DENSE_RANK or ROW_NUMBER depending on what you want.
For example; say a certain part has been ordered 8 times:
3 times with close_date January 29, 2010 (all at exactly the same time),
4 times with close_date January 28, 2010 (all at exactly the same time), and
1 time with close_date January 27, 2010.
If you ask for the last 2 rows:
RANK will give you the 3 rows from January 29. (All 3 have an equal claim to being in the top 2.)
DENSE_RANK will give you the 7 rows from January 28-29 (the last two values , regardless of how many rows have them).
ROW_NUMBER will give you 2 rows from January 29. (Which 2? It's arbitrary unless you add a tie-breaker to the ORDER BY clause.)
All these functions are available in Oracle 8.1.
Similar Messages
-
Query to delete row where column value contains alphabets
Hi,
Could anyone please help me to get this query work.
Query to delete row where column value contains alphabets.
DELETE FROM BIN_ITEM WHERE order_nmb LIKE '%[A-Z]%' || LIKE '%[a-z]%'
Thanks and Regards,
Deekay.RaminHashimzadeh wrote:
SELECT order_nmb FROM BIN_ITEM WHERE regexp_count(order_nmb,'[0-9]') = 0
Ramin Hashimzade
But that won't reject strings like 'gfgG%dgh' which aren't pure alphabetic.
Try:
with test_data as (
select 'ghTYJYEhdfe' str from dual
union
select 'dfF5ssd' from dual
union
select 'rgth*dgheh' from dual
union
select 'ggf{' from dual
union
select 'rwhrhrh' from dual
select *
from test_data
where regexp_instr(str,'[^[:alpha:]]')=0; -
How to accessing current row report column value in Lov Query?
Hi,
which access methods (eg. bind variables, substitutions, ...) for getting the current row report column value can be used in the "Lov Query" property of a report column?
As what I know of and what I have read on the forum there are no bind variables for the report columns. For the "Link Text" property it seems that the column values exist as substitution strings (#COLUMN_NAME#). But they don't work in the Lov Query. => And would be good because of a hard parse each time the Lov query is executed.
The following post (Re: Simulating a correlated sub query in lov
is showing a solution to use package variables for temporary storage of the referenced value, but the only problem with that solution is that if a new record is added with the "Add rows to tabular form" process the package variable still contains the value from the last queried row! Is there a way (variable, APEX package, ...) to determine if the lov query is executed for a new record so that the package can return null?
I know that I could write the package in a way that the value is immediately cleared when lov_pkg.keyval is called (one time read), but then I would have to create several variables if I'm accessing the value multiple times in the query or in another query => I think an one time read solution would be very obscurely.
Thanks for your help
Patrick
http://inside-apex.blogspot.comHi Patrick,
I agree that it's a waste to continually use Ajax to go back to the server to get the contents of a dynamic select list.
There are no bind variables for any row item - but what you do have, as per my previous post, is the value of the data entered by the user in the first row. You can pass this into your application process (using get.add("VARIABLENAME", value)), which can use it to retrieve the correct LOV in your Ajax code - this will give you a "bind variable" that your process can use.
What you could do, however, is generate hidden select lists on your page - one for each possible LOV list and replace the contents of the new row's select list with the contents of the appropriate hidden select list. This is easy to do with javascript (using innerHTML functions). Obviously, though, the usefulness of this depends on the number and size of the select lists.
Even if you don't generate them to start with, you can keep a copy of any select lists returned by Ajax in the DOM for use on new rows. So, if you have retrieved a select list, you will have a copy of it in DOM which you can then copy into the new row. If you don't have the list in DOM, use Ajax to get it, store a copy of it and copy it into the new row.
Which method you use will depend on the number/size of select lists needed. If they are few in number and/or size, I would suggest generating hidden lists. If they are large, use Ajax to get them once, store them and then retrieve them from the DOM when needed.
There is another thread here where Arie recommends going to the server every time to make sure you get the most up-to-date data for the lists. If you want to follow this advice, for this reason, use get.add("VARIABLENAME", value) to pass the value to your process. If this is not an issue, you can use one of the other methods I outlined above.
Regards
Andy -
Return Code - Query for Multiple Rows as XML
Hi,
I'm executing an MSSQL stored procedure through the "Query for Multiple Rows as XML" activity in LiveCycle ES. I do this through a call statement such as this:
{ call MyStoredProc(?) }
This works great, the stored procedure always returns a record set (with or without records). I use this activity rather than "Call Stored Procedure" because I can transform the record set into XML right away within this activity. Unfortunately any exception arising from invoking this stored procedure cannot be handled within the workflow as this activity does not have an exception handler (lightning bolt). In an attempt to handle at least some exceptions we have decided to use try/catches within the stored procedures and return different error codes. Now the problem I am faced with is that there is no way to retrieve the returned code within any of the SQL activities. We don't want to have to write an execute script for each of these SQL calls. Is there any way to do this? Seems like I'm 95% there.
Thanks
NicThanks for the offer, unfortunately we would need something certified by Adobe.
Nic -
Hi, I would like to know how can i break the value for a row and column once i have converted the image to the array. I wanted to make some modification on the element of the array at a certain position. how can i do that?
At the moment (as per attachhment), the value of the new row and column will be inserted by the user. But now, I want to do some coding that will automatically insert the new value of the row and the column ( I will use the formula node for the programming). But the question now, I don't know how to split the row and the column. Is it the value of i in the 'for loop'? I've tried to link the 'i' to the input of the 'replace subset array icon' , but i'm unable to do it as i got some error.
Please help me!
For your information, I'm using LABView 7.0.Hi,
Thanks for your reply.Sorry for the confusion.
I manage to change the array element by changing the row and column value. But, what i want is to allow the program to change the array element at a specified row and column value, where the new value is generated automatically by the program.
Atatched is the diagram. I've detailed out the program . you may refer to the comments in the formula node. There are 2 arrays going into the loop. If a >3, then the program will switch to b, where if b =0, then the program will check on the value of the next element which is in the same row with b but in the next column. But if b =45, another set of checking will be done at a dufferent value of row and column.
I hope that I have made the problem clear. Sorry if it is still confusing.
Hope you can help me. Thank you!!!!
Attachments:
arrayrowncolumn2.JPG 64 KB -
Oracle SQL query for getting specific special characters from a table
Hi all,
This is my table
Table Name- Table1
S.no Name
1 aaaaaaaa
2 a1234sgjghb
3 a@3$%jkhkjn
4 abcd-dfghjik
5 bbvxzckvbzxcv&^%#
6 ashgweqfg/gfjwgefj////
7 sdsaf$([]:'
8 <-fdsjgbdfsg
9 dfgfdgfd"uodf
10 aaaa bbbbz#$
11 cccc dddd-/mnm
The output has to be
S.no Name
3 a@3$%jkhkjn
5 bbvxzckvbzxcv&^%#
7 sdsaf$([]:'
8 <-fdsjgbdfsg
10 aaaa bbbbz#$
It has to return "Name" column which is having special characters,whereas some special chars like -, / ," and space are acceptable.
The Oracle query has to print columns having special characters excluding -,/," and space
Can anyone help me to get a SQL query for the above.
Thanks in advance.You can achieve it in multiple ways. Here are few.
SQL> with t
2 as
3 (
4 select 1 id, 'aaaaaaaa' name from dual union all
5 select 2 id, 'a1234sgjghb' name from dual union all
6 select 3 id, 'a@3$%jkhkjn' name from dual union all
7 select 4 id, 'abcd-dfghjik' name from dual union all
8 select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
9 select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
10 select 7 id, 'sdsaf$([]:''' name from dual union all
11 select 8 id, '<-fdsjgbdfsg' name from dual union all
12 select 9 id, 'dfgfdgfd"uodf' name from dual union all
13 select 10 id, 'aaaa bbbbz#$' name from dual union all
14 select 11 id, 'cccc dddd-/mnm' name from dual
15 )
16 select *
17 from t
18 where regexp_like(translate(name,'a-/" ','a'), '[^[:alnum:]]');
ID NAME
3 a@3$%jkhkjn
5 bbvxzckvbzxcv&^%#
7 sdsaf$([]:'
8 <-fdsjgbdfsg
10 aaaa bbbbz#$
SQL> with t
2 as
3 (
4 select 1 id, 'aaaaaaaa' name from dual union all
5 select 2 id, 'a1234sgjghb' name from dual union all
6 select 3 id, 'a@3$%jkhkjn' name from dual union all
7 select 4 id, 'abcd-dfghjik' name from dual union all
8 select 5 id, 'bbvxzckvbzxcv&^%#' name from dual union all
9 select 6 id, 'ashgweqfg/gfjwgefj////' name from dual union all
10 select 7 id, 'sdsaf$([]:''' name from dual union all
11 select 8 id, '<-fdsjgbdfsg' name from dual union all
12 select 9 id, 'dfgfdgfd"uodf' name from dual union all
13 select 10 id, 'aaaa bbbbz#$' name from dual union all
14 select 11 id, 'cccc dddd-/mnm' name from dual
15 )
16 select *
17 from t
18 where translate
19 (
20 lower(translate(name,'a-/" ','a'))
21 , '.0123456789abcdefghijklmnopqrstuvwxyz'
22 , '.'
23 ) is not null;
ID NAME
3 a@3$%jkhkjn
5 bbvxzckvbzxcv&^%#
7 sdsaf$([]:'
8 <-fdsjgbdfsg
10 aaaa bbbbz#$
SQL> -
Query to convert Row to column - Re-posting
Hi all,
i am re-posting the same requirement, please do the needful.
I need a query to convert row value into column delimited by ','
create table tb_row_2_col (id number,val varchar2(100));
insert into tb_row_2_col values (1,'col1');
insert into tb_row_2_col values (1,'col2');
insert into tb_row_2_col values (1,'col3');
insert into tb_row_2_col values (2,'col4');
insert into tb_row_2_col values (2,'col5');
commit;
SQL> select * from tb_row_2_col;
ID VAL
1 col1
1 col2
1 col3
2 col4
2 col5
SQL>
if i execute a query the output should be like this
ID VAL
1 col1,col2,col3
2 col4,col5
Thanks in advance
S. Sathish KumarMost repeated question in the forum..
SQL> select id,max(ltrim(sys_connect_by_path(val,','),',')) res
2 from (select id,val,
3 row_number() over(partition by id order by val) rn
4 from tb_row_2_col)
5 start with rn = 1
6 connect by prior rn = rn -1
7 and prior id = id
8 group by id;
ID RES
1 col1,col2,col3
2 col4,col5<br>
Message was edited by:
jeneesh
Check here for variations.. -
Query to convert Row to column
Hi all,
I need a query to convert row value into column delimited by ','
create table tb_row_2_col (id number,val varchar2(100));
insert into tb_row_2_col values (1,'col1');
insert into tb_row_2_col values (1,'col2');
insert into tb_row_2_col values (1,'col3');
insert into tb_row_2_col values (2,'col4');
insert into tb_row_2_col values (2,'col5');
commit;
SQL> select * from tb_row_2_col;
ID VAL
1 col1
1 col2
1 col3
2 col4
2 col5
SQL>
if i execute a query the output should be like this
ID VAL
1 col1,col2,col3
2 col4,col5
Thanks in advance
S. Sathish KumarOr look for aggregation techniques against the forum helping by the search feature (top-right of the current page).
Nicolas. -
Querying the schema for table name with column value!
In my schema i have 500+ tables and other objects.
i have a column with the name BO_PRODUCT_CODE.
I wants to know in what tables the value of BO_PRODUCT_CODE='FX03'.
i have query the user_tab_columns which gives me the result with 90 tables having the column BO_PRODUCT_CODE.
What is query which will give me the exact number/name of the table whose column value is FX03. ie, BO_PRODUCT_CODE='FX03'.Hi you can use this approach:
BEGIN
v_str VARCHAR2(250);
v_count NUMBER :=0;
DECLARE
FOR loop_tbl IN ( SELECT DISTINCT table_name FROM USER_TAB_COLUMNS
WHERE column_name ='BO_PRODUCT_CODE' )
LOOP
v_str := 'SELECT COUNT(*) FROM ' || loop_tbl.table_name || ' WHERE BO_PRODUCT_CODE=||'''' ||'FX03' || '''' '
EXECUTE IMMEDIATE v_str INTO v_count ;
IF v_count > 0 THEN
DBMS_OUTPUT.PUT_LINE ('Table Name :'|| loop_tbl.table_name || ' Count :'||v_count);
END IF;
v_count :=0;
END LOOP;
EXCEPTION
WHEN others THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
Please remove if any syntax error.
Regards -
Query for deleting rows older than 25?
Am trying to delete rows older than 25... How would the query for this be like? I tried this "DELETE FROM DB LIMIT 25,100" But getting errors...
what is older than 25? Does it mean with id greater then 25?
then you should have a query like
DELETE FROM tableName WHERE id > 25 -
Coverting a Row into Columns values
Hi SQL Expert Friends,
I have a row which contains 6 columns where I want that data to be shown in the form of columns as shown here:
From:
select item1, item2, item3, amt1, amt2, amt3 from item_table where sno=1; <----- returns 1 row as below
ITEM1 ITEM2 ITEM3 AMT1 AMT2 AMT3
AAA BBB CCC 10.00 20.00 15.00
Data explanation: item1's (AAA) price is amt1 (10.00), item2's (BBB) price is amt2 (20.00) and item3's (CCC) price is amt3 (15.00). OK.
Now I want that data to convert into columns as shown here:
To:
ITEMS AMT
AAA 10.00
BBB 20.00
CCC 30.00
Please help me friends, I want a SQL to display this data.
I found one query which converts a row into columns, but this does not serve my requirement: [for your reference only]
SQL> select substr( the_string
, decode( level, 1, 1, instr(the_string,',',1,level-1)+1)
, decode( instr(the_string,',',1,level), 0, length(the_string), instr(the_string,',',1,level) - decode( level, 1, 0, instr(the_string,',',1,level-1))-1)
) the_value
from ( select (select item1||','||item2||','|| item3 from item_table where sno=1) ITEMS
from DUAL)
connect by level <= length(the_string)-length(replace(the_string,','))+1
Thanks and REgards,
KiranHi, Kirtan,
kiran wrote:
... I want to learn this query, If you could explain me this how it works, then it will definitely helps me.If you don't understand a query that involves sub-queries, make sure you understand the sub-queries first. Run them separately, and study the results.
In this case, the only sub-query is cntr. Run it separately, like this:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 3
SELECT *
FROM cntr;Output:
` N
1
2
3Why did I use the number 3 in "LEVEL <= 3"? Because each row will be unpivoted onto 3 rows. You could make this number 2, or 5, or 25 if that's how many rows you want in the output.
Once you understand the sub-queries, try running the main query. Include the raw values of all columns that play any part in the output. For example:
WITH cntr AS
SELECT LEVEL AS n
FROM dual
CONNECT BY LEVEL <= 3
SELECT CASE cn.n
WHEN 1 THEN co.city1
WHEN 2 THEN co.city2
WHEN 3 THEN co.city3
END AS cities
, CASE cn.n
WHEN 1 THEN co.population1
WHEN 2 THEN co.population2
WHEN 3 THEN co.population3
END AS population
, co.* -- For testing/understanding only
, cn.* -- For testing/understanding only
FROM continent co
CROSS JOIN cntr cn
WHERE co.country = 'America'
;Output:
` POPUL POPUL POPUL POPUL
CITIES ATION COUNTRY CITY1 CITY2 CITY3 ATION1 ATION2 ATION3 N
Phoenix 20000 America Phoenix Los Angeles Chicago 20000 15000 10000 1
Los Angeles 15000 America Phoenix Los Angeles Chicago 20000 15000 10000 2
Chicago 10000 America Phoenix Los Angeles Chicago 20000 15000 10000 3Why are there 3 rows of output? There are 3 rows in the cntr "table", and 3 rows in the continent table. Of these 3 * 3 = 9 rows, only the 3 rows shown above meet the condition in the WHERE clause. (Comment out the WHERE clause and try it again, if you want to see how that works.) Can you see how you get the output (the first 2 columns above) given all the data in the original columns? If not, ask a more specific question about the part you don't understand. -
How to get the Row and Column values in ALV (without using Objects)
Hi All,
I need to get the Row / Column when double click is used in ALV, I can use the double click event for this. However, I do not want to use the Object Oriented ALV. I want to implement the same functionality using general (using functions) ALV.
Is there any way to get the row / column values for a Generia (non-OOPs) ALV report.
Please help.
Thanks,
Vishal.Hello,
The only think you have to do is to get the index where the user clicked, and then read the internal table you sent to the alv
CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
EXPORTING
i_callback_program = 'prg_name'
i_callback_pf_status_set = 'SET_PF_STATUS'
i_callback_user_command = 'USER_COMMAND' " this is to the click event!!
i_callback_top_of_page = 'TOP_OF_PAGE'
is_layout = alv_layout
it_fieldcat = alv_fieldcat
i_save = 'A'
it_events = alv_events[]
TABLES
t_outtab = i_totmez. ---> TOUR IT.
IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
" then....
FORM user_commandUSING r_ucomm TYPE sy-ucomm
ls_selfield TYPE slis_selfield.
" r_ucomm -> HAS THE STATUS
" ls_selfield-tabindex -> HAS THE SELECTED INDEX
" THEN READ THE INTERNAL TABLE
" HERE YOU WILL HAVE THE SELECTED ROW
READ TABLE i_totmez INDEX ls_selfield-tabindex.
ENDFORM.
cheers,
Gabriel P. -
Query for one row of each distinct column value
lets say theres table employee with columns name, id, and title. How do you get one row for each distinct title. Whatever row it is doesnt matter as long as your result set covers every possible employee title. How can I do this? thanks
Hi,
I think you're asking about a Top-N Query .
Since you didn't post a version of your table, I'll use scott.emp to illustrate.
The following query shows exactly one row of output for each distinct job:
WITH got_r_num AS
SELECT empno, ename, job
, ROW_NUMBER () OVER ( PARTITION BY job
ORDER BY ename
) AS r_num
FROM scott.emp
SELECT empno, ename, job
FROM got_r_num
WHERE r_num = 1
;Output:
` EMPNO ENAME JOB
7902 FORD ANALYST
7876 ADAMS CLERK
7698 BLAKE MANAGER
7839 KING PRESIDENT
7499 ALLEN SALESMANThe rows you see are actual rows from the table, not aggregates. That is, you can be certain that there is a row in the table with empno=7902, ename='FORD' and job='ANALYST'.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and also post the results you want from that data.
If the desired results are not unique, that is, if you'd be equally satisfied with a number of different result sets, then post a couple of examples from the same sample data. -
Refining SQL Replacement for Oracle's WM_CONCAT Function (Pivoting Rows to column)
Greetings,
I am moving a query from Oracle SQL to Microsoft SQL and am having some difficulty with the transition. Part of my code (listed here) used to pivot the data and display RESULT_VALUE
by the CPI_SEQ . In Oracle this was easy to do by using the function: WM_CONCAT.
I have been ‘Googling’ for the non-Oracle way to achieve this and stumbled on to the “STUFF((SELECT…)”
method. This almost works for me except that it places everything into one cell, whereas
I need to concatenate RESULT_VALUE by CPI_SEQ (the CPI_SEQ is the unique ID). The current code gives me this:
RESULTS
Anxiety, Depression, Diabetes,
COPD, ARDS
Whereas I want my code to present it this way instead
CPI_SEQ
RESULTS
22
Anxiety, Depression
44
Diabetes
46
COPD, ARDS
SELECT (STUFF((SELECT ',' + RESULT_VALUE
FROM
SELECT DISTINCT
C1.CPI_Seq AS CPI_SEQ,C1.Result_Value AS RESULT_VALUE
,count(FCurrent.Field_Name) "Current"
,count(FPast.Field_Name) "Past"
,Count(*) Count
,CASE
When count(FCurrent.Field_Name) > 0 and count(FPast.Field_Name) >0 and count(Fcurrent.Field_Name)+ count(FPast.Field_Name) = Count(C1.PF_RESULT_SEQ) Then CONCAT(C1.Result_Value,'(C/P)')
When count(FCurrent.Field_Name) > 0 and count(FPast.Field_Name) =0 and count(Fcurrent.Field_Name)+ count(FPast.Field_Name) = Count(C1.PF_RESULT_SEQ) Then CONCAT (C1.Result_Value,'(C)')
When count(FCurrent.Field_Name) = 0 and count(FPast.Field_Name) >0 and count(Fcurrent.Field_Name)+ count(FPast.Field_Name) = Count(C1.PF_RESULT_SEQ) Then CONCAT(C1.Result_Value,'(P)')
End Result
From
[AnalyticsDW].[dbo].[rr_stag_PF_Results] A1
join [AnalyticsDW].[dbo].[rr_stag_PF_Results] C1 on A1.PF_Result_Seq = C1.PF_Result_Seq
join [AnalyticsDW].[dbo].[rr_PF_Fields_Dept] FCurrent on A1.PF_Result_Seq = FCurrent.RES_SEQ
AND FCurrent.Field_Name = 'Current'
AND A1.Label_Seq in('187582', '187576','187612','187600','187618','187612')
left join [AnalyticsDW].[dbo].rr_PF_Fields_Dept FPast on A1.PF_Result_Seq = FPast.Res_Seq
AND FPast.Field_Name = 'Past'
AND A1.Label_Seq in('187583', '187577','187613','187601','187619','187613')
WHERE
A1.Result_Value ='Yes'
AND (C1.Result_Value in ('Dyspnea', 'Confusion','Pressure Ulcer', 'Stasis Ulcer','Depression','Anxiety'))
GROUP BY
C1.CPI_Seq,
C1.Result_Value
) L1
FOR XML PATH('')),1,2,'')) RESULTS;With CTE
AS
SELECT
C1.CPI_Seq AS CPI_SEQ,
C1.Result_Value AS RESULT_VALUE
From
[AnalyticsDW].[dbo].[rr_stag_PF_Results] A1
join [AnalyticsDW].[dbo].[rr_stag_PF_Results] C1 on A1.PF_Result_Seq = C1.PF_Result_Seq
join [AnalyticsDW].[dbo].[rr_PF_Fields_Dept] FCurrent on A1.PF_Result_Seq = FCurrent.RES_SEQ
AND FCurrent.Field_Name = 'Current'
AND A1.Label_Seq in('187582', '187576','187612','187600','187618','187612')
left join [AnalyticsDW].[dbo].rr_PF_Fields_Dept FPast on A1.PF_Result_Seq = FPast.Res_Seq
AND FPast.Field_Name = 'Past'
AND A1.Label_Seq in('187583', '187577','187613','187601','187619','187613')
WHERE
A1.Result_Value ='Yes'
AND (C1.Result_Value in ('Dyspnea', 'Confusion','Pressure Ulcer', 'Stasis Ulcer','Depression','Anxiety'))
GROUP BY
C1.CPI_Seq,
C1.Result_Value
SELECT CPI_Seq,
STUFF((SELECT ',' + Result_Value
FROM CTE
WHERE CPI_Seq = c.CPI_Seq
FOR XML PATH(''),TYPE).value('.','varchar(max)'),1,1,'') AS Results
FROM (SELECT DISTINCT CPI_Seq FROM CTE)c
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs -
Oracle Pivot query regardless of number of columns
Hi, I have a requirement to create a view by pivoting all records associated with primary record regardless of the number of records, but... the LEVELID marked as Primary must be the first column left to right. The order of columns left to right after that do not matter.
There can be up to 18 CODES associated with a CLM but the amount is variable.
Thank you for your time.
create table
id_levels
(clm varchar2(12),
code varchar2 (12),
levelid varchar2 (12));
insert into id_levels select '1','15','Primary' from dual;
insert into id_levels select '1','42','Secondary' from dual;
insert into id_levels select '1','44','Third' from dual;
insert into id_levels select '1','41','Secondary' from dual;
insert into id_levels select '2','3','Primary' from dual;
insert into id_levels select '2','4','Secondary' from dual;
insert into id_levels select '3','24','Primary' from dual;
insert into id_levels select '3','15','Secondary' from dual;
insert into id_levels select '3','15','Secondary' from dual;
insert into id_levels select '3','16','Third' from dual;
insert into id_levels select '4','12','Primary' from dual;
insert into id_levels select '4','67','Third' from dual;
insert into id_levels select '5','13','Primary' from dual;
insert into id_levels select '5','24','Secondary' from dual;
insert into id_levels select '5','22','Secondary' from dual;I need the following:
clm | code1 | code2 | code3 | code4 | code5 | code6 | code7 | code8 | code9 | code10
1 | 15 | 42 | 44 | 41
2 | 3 | 4
3 | 24 | 15 | 15 | 16
4 | 12 | 67 |
5 | 13 | 24 | 22There can be up to 18 CODES associated with a CLM but the amount is variable.So, when '18 codes' can be considered as fixed, then you can:
SQL> select * from v$version where rownum=1;
BANNER
Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - Production
1 row selected.
SQL> select clm
2 , max(case when rn = 1 then cd end) code1
3 , max(case when rn = 2 then cd end) code2
4 , max(case when rn = 3 then cd end) code3
5 , max(case when rn = 4 then cd end) code4
6 , max(case when rn = 5 then cd end) code5
7 , max(case when rn = 6 then cd end) code6
8 , max(case when rn = 7 then cd end) code7
9 , max(case when rn = 8 then cd end) code8
10 , max(case when rn = 9 then cd end) code9
11 , max(case when rn = 10 then cd end) code10
12 , max(case when rn = 11 then cd end) code11
13 , max(case when rn = 12 then cd end) code12
14 , max(case when rn = 13 then cd end) code13
15 , max(case when rn = 14 then cd end) code14
16 , max(case when rn = 15 then cd end) code15
17 , max(case when rn = 16 then cd end) code16
18 , max(case when rn = 17 then cd end) code17
19 , max(case when rn = 18 then cd end) code18
20 from (
21 select t.clm
22 , t.code cd
23 , t.levelid
24 , row_number() over (partition by clm order by case when levelid = 'Primary' then 1 else t
o_number(code) end) rn
25 from id_levels t
26 )
27 group by clm
28 order by clm;
CLM CODE1 CODE2 CODE3 CODE4 CODE5 CODE6 CODE7 CODE8 CODE9
1 15 41 42 44
2 3 4
3 24 15 15 16
4 12 67
5 13 22 24
5 rows selected.
SQL> set lines 50
SQL> /
CLM CODE1 CODE2
CODE3 CODE4 CODE5
CODE6 CODE7 CODE8
CODE9 CODE10 CODE11
CODE12 CODE13 CODE14
CODE15 CODE16 CODE17
CODE18
CLM CODE1 CODE2
CODE3 CODE4 CODE5
CODE6 CODE7 CODE8
CODE9 CODE10 CODE11
CODE12 CODE13 CODE14
CODE15 CODE16 CODE17
CODE18
5 rows selected.
SQL>
Maybe you are looking for
-
IF and SUBSTR in XML Publisher
Hi I am developing a XML RTF template for a report. All I am trying to do is, if first 4 letters of the data of xml tag ITEM = 'Summ' then print a constant word 'Notes' <?if: xdofx:substr(ITEM,1,4)='Summ'?> Notes<?end if?> I have been trying hard. IF
-
10.4.11 to Snow Leopard
Will Snow Leopard install directly on an older macbook currently running 10.4.11, or are there intermediate steps required?
-
Reg: Validation and substitution
Hi gurus what is the use and difference of Validation and substitution? pls urgent thanks amk
-
Non valuated material consumption in projects
Hi, How to track the non valuated material issued for consumption against network that is not planned in the project? I would require reversing the consumption based on material the contractor returns after actual consumption at the site. My default
-
Need an editor that can show mark up in one mode, and render in the other
Hello All I would like to write an editor into which i can type text (strikes me as a good starting point), the text i enter will contain tags, which are intended to comply with a Wiki style, so for example (Assuming MediaWiki): ''italic'' would resu