SQL & PL/SQL :: Top Row Based On Multiple Columns?
Dec 1, 2011
I have a table with Column A, B, C. I want to write a query to retrieve the top row of A, B combination. i.e, for every unique value of A,B combination I want the row having highest value for C. I tried using rank() function but am not able to get the top row with combination of A,B.
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
I want to delete dups from a table based on 3 columns
with sample_table as ( select '101' as ID1, '201' as ID2, '4' as weight from dual union all select '101' as ID1, '201' as ID2, '5' as weight from dual union all select '105' as ID1, '205' as ID2, '6' as weight from dual union all select '105' as ID1, '205' as ID2, '6' as weight from dual union all [code].........
Desired Output
with sample_table as ( select '101' as ID1, '201' as ID2, '5' as weight from dual union all select '105' as ID1, '205' as ID2, '6' as weight from dual union all select '110' as ID1, '215' as ID2, '9' as weight from dual ) select * from sample_table
How to merge multiple rows into single row (but multiple columns) efficiently.
For example
IDVal IDDesc IdNum Id_Information_Type Attribute_1 Attribute_2 Attribute_3 Attribute_4 Attribute_5 23 asdc 1 Location USA NM ABQ Four Seasons 87106 23 asdc 1 Stats 2300 91.7 8.2 85432 23 asdc 1 Audit 1996 June 17 1200 65 affc 2 Location USA TX AUS Hilton 92305 65 affc 2 Stats 5510 42.7 46 9999 65 affc 2 Audit 1996 July 172 1100
where different attributes mean different thing for each Information_type. For example for Information_Type=Location
Attribute_1 means Country Attribute_2 means State and so on.
For example for Information_Type=Stats
Attribute_1 means Population Attribute_2 means American Ethnicity percentage and so on.
I want to create a view that shows like below:
IDVal IDDesc IDNum Country State City Hotel ZipCode Population American% Other% Area Audit Year AuditMonth Audit Type AuditTime 23 asdc 1 USA NM ABQ FourSeasons 87106 2300 91.7 46 85432 1996 June 17 1200 65 affc 2 USA TX AUS Hilton 92305 5510 42.7 46 9999 1996 July 172 1100
I am attempting to select back multiple values for a specific key on one row. See the example below. I have been able to use the sys_connect_by_path to combine the fields into one field but I am unable to assign them to fields of their own. See the example below
TABLE DETAILS: Policy id plan name 111 A Plan 111 B Plan 111 Z Plan 112 A Plan 112 Z Plan
My desired result is to be able to show the output as follows
Policy ID Plan_1 Plan_2 Plan_3 111 A Plan B Plan Z PLan 112 A Plan Z PLan
I have a result-set which has 4 columns like (Region, PaymentDate, DebitAmt, CreditAmt). This result-set will always have a maximum of one month's records in it.
Suppose, imagine i have data for a month (ex, Mar 1 to Mar 31)...
Now... to aggregate (sum) the amount columns (DebitAmt, CreditAmt) in my resultset based on different date ranges, i wrote a sql like below...
Quote: SELECT REGION, SUM(CASE WHEN PAYMENTDATE BETWEEN MAR 1 AND MAR 15 THEN DebitAmt ELSE 0 END) AS Debit_H1, SUM(CASE WHEN PAYMENTDATE BETWEEN MAR 1 AND MAR 15 THEN CreditAmt ELSE 0 END) AS Credit_H1,
[code]...
My doubt is, in the above query, to aggregate two different columns based on same condition, i am checking the same condition twice...
SQL> SELECT FISCAL_TIME_ID, DATA_ID, M_VALUE, 2 SUM(m_value) OVER (PARTITION BY fiscal_time_id, data_id 3 ORDER BY FISCAL_TIME_ID) AS YTD_VALUE 4 from test11;
Desc Table A (account) Account1_id Account2_id name, empid
Table B (Bill ) BillNo Advertiserid agencyid total vvalue
I need to pick up total value from table B where the unique combination of advertiser-Agency id is the same as the given account1_id -Account2_id combination in table A for each employee id.
In other words my output should be like
Empid | Account_id (should be same as advertiserid)| Account2_id (same as agencyid) | sum(total_value) for this adv-agency combination.....
objective: Get the total value from table B for each unique account1-account2 combination (advertiser-agency in other words) .
I am not sure if I should use a correlated subquery or how to handle the situation....Right now I am just checking the two columns separately like this:
select.......from a,b where b.advertiser_id = a.account1_id and b.agencyid = b.account2id
Is it correct to do so? I have a feeling that I am missing something if I join them separately like this.
I've been having an issue and cannot figure it out for the life. First, here's an example set of the data I'm using so you can see exactly what I'm asking.
Emplid Effdt Effseq
10001 '01-JAN-99' 0
10001 '01-JUL-11' 0
10001 '01-JUL-11' 1
10001 '01-JUL-11' 2
10001 '01-JUL-12' 3
What I need to do here, is obtain 3 rows. The 3 rows I need are rows 1, 4, and 5. I need row 1 because its a completely different date. I need row 5 for the same reason: it's a different date. The issue arises with how I can obtain row 4. The problem is that because rows 2, 3, and 4 all have the same effective date(effdt), SQL Developer just returns one of those rows. Because those 3 rows all have the same effective date(effdt), the tie breaker becomes the effective sequence(effseq) number. When the effective date(effdt) is the same, you need to grab the maximum effective sequence(effseq) number and return that whole row's results such as the emplid, effdt, and effseq. It seems so straight forward and something you can use a subquery for, but its not that simple. Note, that you can specifically use the emplid = 10001 in any specific form because there's many employee id's. Also, the rows will not be in a specific order so you cannot just always grab rows 1, 4, and 5. Some employees may only have a single row in the database, and some may have 50 rows. Everything solely depends on the combination of employee id(emplid), effective date(effdt), and effective sequence(effseq) as the tie breaker.
My issue is with a calculation using columns as variables. below is the code to create and attached is the code (INSERT_data.txt) to fill-in the required tables....
what's required here?
I need to update (through update or simply create new table statement)
BPF(i), BPC(i), BPY(i) of table root_tbl (A) based on InF_IDX, InC_IDX & InY_IDX and OutF_IDX, OutC_IDX & OutY_IDX using BPF(i), BPC(i), BPY(i) from table pvt_vectors_tbl(B).
Join Clause: A.P_NODE=B..P_NODE and A.C_NODE=B.C_NODE and A.P_NODE_Date=B.P_NODE_Date and A.C_NODE_Date=B.C_NODE_Date
the formula are:
BPF(i): if A.InF_IDX<=A.OutF_IDX then FOR i=1 to A.OutF_IDX+1 if i<InF_IDX then A.BPF(i)= A.BPF(i)+ B.BPF(OutF_IDX + i - InF_IDX); else A.BPF(i)=0; i=i+1; else FOR i=1 to A.InF_IDX+1 if i<OutF_IDX then A.BPF(i)= A.BPF(i)+ B.BPF(InF_IDX + i - OutF_IDX); else A.BPF(i)=0; i=i+1; idem for BPc and BPY.
in real word:
* root_tbl table has ~2 million records, 50 BPF(i) columns, 50 BPC(i) columns and ~475 BPY(i) columns * pvt_vectors_tbl has ~50.000 records
when parameter is YES, column having values when Parameter is NO, column having no values
In this scenario, how can i skip the column with space when parameter is NO because the column exist in middle of columns in report and Present with space when parameter is YES.
I've got a report with two lov's, where the user is able to change the lov value and submit it. After submit the status of the item P100_status will be changed in Disable. Based on this value the lov's must be disables with apex_disabled. How can I disable these columns based on the value of P100_status?
I have one table , with one column having 2,3 or 4 machine codes , i need to display them as each row per machine code will it be possible to do as i have thousands of records similar to the test case and which i had to do it manually in excel and then upload it back.
insert into ow_oper_setup VALUES ('1270','1270001','W165','IR HO BV ') insert into ow_oper_setup VALUES ('1270','1270001','W1332','IR BV ') insert into ow_oper_setup values ('1270','1270001','W1367','RE HO SC BV ') insert into ow_oper_setup values ('1270','1270001','W389','RE HO SC BV')
commit;
SELECT * FROM ow_oper_Setup;
WO_NOMRK_NOPOS_NOMC_CODE 12701270001W165IR HO BV 12701270001W1332IR BV 12701270001W1367RE HO SC BV 12701270001W389RE HO SC BV
--i want the output in the following way or the same table data to be replaced as below
with tmp_tbl as (select 'H1' as hh_id, 'C1' as cust_id, 2 as f_rnk, 'F' as gender, to_date('20130102','YYYYMMDD') as purch_dt, to_date('20100203','YYYYMMDD') first_dt from dual union select 'H1' as hh_id, 'C2' as cust_id, 1 as f_rnk, 'M' as gender, to_date('20130102','YYYYMMDD') as purch_dt, to_date('20100303','YYYYMMDD') first_dt from dual union select 'H1' as hh_id, 'C3' as cust_id, cast(null as number) as f_rnk, 'U' as gender, to_date('20130103','YYYYMMDD') as purch_dt, [code].....
Now i need to rank each cust_id in each hh_id based on below conditions.
1) If atleaset one cust_id in hh_id has f_rnk then gender 'F' with highest f_rnk (more then one F with same f_rnk then the one with oldest first_dt), if no 'F' then gender 'U' with highest f_rnk ((more then one F with same f_rnk then the one with oldest first_dt)), if no 'F' and 'U' then consider 'M' (more then one M with same f_rnk then the one with oldest first_dt).
2) If the above is not met (no cust_id in hh_id has f_rnk populated) then i've to rank based on purch_dt. Gender 'F' with recent purch_dt (if more than one F in household with same purch_dt then the one with oldest first_dt), if no 'F' then gender 'U' with recent purch_dt (if more than one U in household with same purch_dt then one with oldest first_dt), if no 'F' and 'U' then consider 'M' (more than one M in household with same purch_dt then the one with oldest first_dt).
3) If the above criteria is also not met, then rank based on gender_cd. Gender 'F' will have first preference then 'U' and then 'M'.
My output :
HH_ID CUST_ID F_RNK GENDER PURCH_DT FIRST_DT F_RNK_RANK PURCH_RANK GENDER_ONLY_RANK ----- ------- ---------- ------ ----------- ----------- ------------ ------------ ----------------- H1 C1 2 F 1/2/2013 2/3/2010 1 H1 C2 1 M 1/2/2013 3/3/2010 2 H1 C3 U 1/3/2013 4/3/2010 3 H2 C4 F 4/3/2013 10/2/2009 2 H2 C5 M 5/5/2013 8/8/2010 1 H3 C6 F 5/6/2008 1 H3 C6 M 7/8/2010 2
I've tried below query with one condition, but it's giving f_rnk_rank for all records. How can i include multiple conditions in the rank function.
with tmp_tbl as (select 'H1' as hh_id, 'C1' as cust_id, 2 as f_rnk, 'F' as gender, to_date('20130102','YYYYMMDD') as purch_dt, to_date('20100203','YYYYMMDD') first_dt from dual union select 'H1' as hh_id, 'C2' as cust_id, 1 as f_rnk, 'M' as gender, to_date('20130102','YYYYMMDD') as purch_dt, to_date('20100303','YYYYMMDD') first_dt from dual union select 'H1' as hh_id, 'C3' as cust_id, cast(null as number) as f_rnk, 'U' as gender, to_date('20130103','YYYYMMDD') as purch_dt, s hh_id, 'C5' as cust_id, [code]....
My requirement is to concatenate two column values and place them in a new column.I have done it using self join but it limits the purpose,meaning when I have more than 2 values for grouped columns then it won't work.How to make this dynamic,so that for any number of columns grouped,I can concatenate.
SELECT a.co_nm, a.mnfst_nr, a.mnfst_qty, a.mnfst_nr || ':' || a.mnfst_qty || ';' || b.mnfst_nr || ':' || b.mnfst_qty FROM vw_acao_critical a JOIN vw_acao_critical b ON a.co_nm = b.co_nm AND a.mnfst_nr = b.mnfst_nr [code]......
What will be the case when I need to concatenate for more number of values.
like when co_nm has three bahs and manfst_nr and manfst_qty has 3 values for each for bah.and if three are having same_mnfst nr then I should use something dynamic.how to achieve this.
I have a requirement where i need to retain latest 3 records based on creation date for each customer_id and delete the older records. The customer_ id or contract_number data in the test table are not unique.
Sample Table Script:
CREATE TABLE TEST ( CUSTOMER_ID VARCHAR2(120 BYTE) NOT NULL, CONTRACT_NUMBER VARCHAR2(120 BYTE) NOT NULL, CREATION_DATE DATE NOT NULL ); [code]...
I need to join ISSUED_REMOVED Table with ITL Table. having each quantity each row.
Eg. If a unit Serial no '354879019900009' has a part (1015268) issued 8 times and then unissued 4 times so finally the part was issued 4 times. so I need 4 rows to show for each qty 1 for that part and unit serial number.
create table ISSUED_REMOVED_ITEM (REPAIRED_ITEM_ID, ISSUED_REMOVED_ITEM_ID, ISSUED_PART_ID, OPER_ID, ISSUED_REMOVED_QUANTITY) as select 122013187, 1323938, 1015268, 308, 2 from dual union all select 122013187, 1323939, 1015269, 308, 2 from dual union all select 122013187, 1323940, 1015268, 308, 2 from dual union all select
[code]....
-- The way I need to join the Issued_Removed Table
select * from ITL_TEST ITL left join issued_removed_item iri on iri.REPAIRED_ITEM_ID = ITL.ITEM_ID --ITL.ITEM_ID --rlsn2.item_id --126357561 and iri.oper_id = 308 --in ( 308, 309)
CREATE TABLE test1 (strt_num NUMBER , end_num NUMBER , des VARCHAR2(5), CONSTRAINT pk_strt_num PRIMARY KEY (strt_num) ); INSERT INTO test1 VALUES (5, 8, 'GC'); INSERT INTO test1 VALUES (10, 25, 'AB'); INSERT INTO test1 VALUES (12, 35, 'PC'); INSERT INTO test1 VALUES (22, 65, 'LJ');
SELECT * FROM test1
STRT_NUM END_NUM DES -------------- ------------ ------------- 5 8 GC 10 25 AB 12 35 PC 22 65 LJ
The requirement is the records should be split based on below conditions
1. Split only those records WHERE (end_num - strt_num) > 10 2. If TRUNC((end_num - strt_num)/10) = n, then n + 1 number of rows should be created for that record 3. While splitting the records, -> For first record , START_NUM = Original STRT_NUM and END_NUM = START_NUM + 10 -> Second record , STRT_NUM = previous END_NUM + 1 and END_NUM = previous END_NUM + 10 And this should continue for all records except the last record -> For last record, STRT_NUM = previous END_NUM + 1 AND END_NUM = Original END_NUM
This table has 5 million records. Only for 2000 records (end_num - strt_num) > 10.
Expected Output.
STRT_NUM END_NUM DES ------------- -------- --------- 5 8 GC -- No chage, END_NUM - STRT_NUM < 10
I have a query to pull the first contact of students.
The table has all contacts like parent/guardian, friends family, emergency contact etc.
I would like to the first primary contact in this order, 1. initial contact, 2. same as student address and also have to be parents, 3. live with and also a parent, 4. parents 5. friends.
I don't know how to pull 2 and 3 . because it looks like it needs to concatenate the columns.
here is my initial query
Select Min(U2.Id) Keep (Dense_Rank First Order By U2.Initial_Contact Desc, U2.Same_As_Students_Address Desc,u2.lives_with DESC,U2.Guardian Desc) From Contacts
how to achieve 2 and 3?
The table script is attached. All the above columns are 1 or 0.
I am trying to validate a monthly report so was trying to write queries to get different criteria into one table. So my first query returns all the product,second query returns all the enrolled customers, 3rd query returns all the cancelled customers and 4th query returns all the newly enrolled for a month. Is there a way I can pass the first query results into 1st column, 2 query results into 2nd column, 3 query results into 3rd column and so on.
I tired writing the SQL several different ways and have spent a day on it and still cannot figure it out. I am using SQL Developer.
select * from nrc_trans_descr where type_id_nrc=60013 -- it has 18 columns and i have hard coded 60013 for simplification here.60013 is derived from 3 other table Output is ( it can have many rows too.typically for each type_id_nrc there is one row ).
TYPE_ID_NRC TRIGGER_STATUS INSTALLMENT_TYPE_ID_NRC --------------------------------------------------------------------- 60013 0 61013 i have to pass TYPE_ID_NRC and INSTALLMENT_TYPE_ID_NRC to restriction_id column in a different table. currently i am doing like this select * FROM DISCOUNT_RESTRICTIONS WHERE discount_id in (12085,12086) and (restricted_id in ( select type_id_nrc from nrc_trans_descr where type_id_nrc=60013) or restricted_id in ( select installment_type_id_nrc from nrc_trans_descr where type_id_nrc=60013));
am using ORACLE 10GR2(solution for 11gr2 is welcome too)
ID Status description Tracking ID 1 Strat Frog 1 2 Start Dog 2 3 Process Frog 1 4 Completed Dog 2 5 Start Rabbit 3 6 Error Frog 1 7 Stop Rabbit 3 8 Start Elephant 4 9 process Elephant 4 10 Start Human 5 11 Stop Human 5 12 Start Butterfly 6 13 completed Butterfly 6 14 start lion 7 15 error lion 8 16 complted lion 8 17 start tiger 9 18 error tiger 9
select * from Table-Name where datetime < to_date('2012/12/06:06:00:00', 'yyyy/mm/dd:hh24:mi:ss') And datetime > to_date('2012/12/04:22:00:00', 'yyyy/mm/dd:hh24:mi:ss')And not description in (Select * from Table-Name where Status like ('%Complete%' or Status like '%stop%') and description in (Select description from Table-Name where Status Like '%start%'));
Result should be " Frog and Elephant and tiger"
Start of every record(descrpition --status is Start) End of every record ( status is stop or done or completed) status process is in btwn (their will be mulitple records with name s//y to process...ie. process 1 ...process 2...process 3 )
I've read so many different pages on this topic but I can't seem to get my query the way it needs to be. Here's the query:
select admitnbr, lastname||', '||firstname||' '||finitial, hphone, mobile, wphone, med_rec, dob from patients join schedule using (key_patien) join adtmirro using (key_patien) where appt_state = 'ON HOLD'
Because patients in my database can have multiple appointments "on hold" there are duplicates in the results. I only need 1 record per patient in order to forward this information into an automated dialer to contact that patient. I do NOT want to call the patient over and over again. Once will suffice. I'm trying to make a distinction on the column 'med_rec'. One row per 'med_rec' will be awesome but I can't find a way to create a distinct on that column.
i have downloaded ireports latest version (3.6.0) for working with jasper reports (3.5.2) and creating reports;How can I change the orientation of a 4 columns report in order to generate the columns starting from the right side.I need to generate a multiple columns report in arabic and it should be done from right to left.
I need to write a script which copies 4 col data from one table to another table. there are three tables
cwat_curr_mst and cwat_assigned_customer and cwat_assignment_mst. Cwat curr mst has PK curr_id and cwat_assigned_customer has PK assignment_id. Also cwat_assigned_customer has customer_id. In cwat_assignment_mst has Curr_id and Assignment_ID.
cwat_curr_mst and cwat_assigned_customer tables has 4 cols in common they are ASRT_SNM_NO, SNM_NO, FLORIDA_NO, CBRN_NO.
So from curr_mst all these 4 cols data needs to come/copy into cwat_assigned_customer.