Returning results as a single-row sub query.
Hi,
This is my current query
WITH car as (SELECT 'FORD' make FROM DUAL UNION SELECT 'TOYOTA' make FROM DUAL UNION SELECT'BMW' make FROM DUAL UNION SELECT 'FIAT' make FROM DUAL)
SELECT * FROM CARWhich returns:-
BMW
FIAT
FORD
TOYOTAHowever the actual output required:-
'BMW, FIAT, FORD, TOYOTA'i.e. all returned on one row.
Any ideas on how to do this??
Thanks in advance!
David
Hi,
Or: use row_number() and connect by:
SQL> select ltrim(sys_connect_by_path(make,', '),', ') make
2 from (
3 WITH car as (SELECT 'FORD' make FROM DUAL union
4 SELECT 'TOYOTA' make FROM DUAL UNION
5 SELECT'BMW' make FROM DUAL UNION
6 SELECT 'FIAT' make FROM DUAL
7 )
8 SELECT make
9 , row_number() over (order by make) rn
10 FROM CAR
11 )
12 where connect_by_isleaf = 1
13 connect by rn = prior rn + 1
14 start with rn = 1
15 order by make
16 ;
MAKE
BMW, FIAT, FORD, TOYOTA
1 row selected.Edited by: hoek on Jun 5, 2009 12:56 PM
But how could I even think I'd type faster than Lightnin' Blushadow? ;)
Similar Messages
-
ORA-01427:single-row sub query returns more than one row (group by)
Hello every one, I am very new to this field , and Right now I am working with this sql, where BEG_BAL_WKST,WKST_RECEIVED_NUM,WKST_PROCESSED_NUM,WKST_CANCELED_NUM are needs to be grouped by,but I am getting the "single-row sub query returns more than one row".
This is the query I am using in my source qualifier:
select
SUM(tmp.WIP_TO_BILL_LOC_AMT) AS WIP_TO_BILL_LOC_AMT,
sum(tmp.REALIZATION_LOC_AMT) AS REALIZATION_LOC_AMT,
SUM(tmp.NEG_REAL_LOC_AMT) AS NEG_REAL_LOC_AMT,
sum(tmp.POS_REAL_LOC_AMT) AS POS_REAL_LOC_AMT,
sum(tmp.BILL_IN_ADVANCE_LOC_AMT) AS BILL_IN_ADVANCE_LOC_AMT,
sum(tmp.CARRY_FORWARD_LOC_AMT) AS CARRY_FORWARD_LOC_AMT,
sum(tmp.BILL_TO_CLIENT_LOC_AMT) AS BILL_TO_CLIENT_LOC_AMT,
sum(tmp.REMAIN_WIP_TO_BILL_LOC_AMT) REMAIN_WIP_TO_BILL_LOC_AMT,
sum(tmp.AR_INV_AMT) AS AR_INV_AMT,
sum(tmp.AR_TAX_AMT) AS AR_TAX_AMT,
tmp.BEG_BAL_WKST_NUM AS BEG_BAL_WKST_NUM,
tmp.WKST_RECEIVED_NUM AS WKST_RECEIVED_NUM,
tmp.WKST_PROCESSED_NUM AS WKST_PROCESSED_NUM,
tmp.WKST_CANCELED_NUM AS WKST_CANCELED_NUM,
tmp.DURATION AS DURATION,
tmp.NUM_DAYS AS NUM_DAYS,
tmp.NUM_HOURS AS NUM_HOURS,
tmp.NUM_MINUTES AS NUM_MINUTES,
tmp.NUM_SECONDS AS NUM_SECONDS,
tmp.LEAD_PROJECT_OFFICE_CODE AS LEAD_PROJECT_OFFICE_CODE,
tmp.LEAD_PROJECT_TEAM_CODE AS LEAD_PROJECT_TEAM_CODE,
tmp.ORG_ID AS ORG_ID,
tmp.RPT_DATE AS RPT_DATE,
tmp.RPT_DATE_WID AS RPT_DATE_WID,
tmp.LOCAL_CURR_CODE AS LOCAL_CURR_CODE,
tmp.USD_EXCH_RATE AS USD_EXCH_RATE,
tmp.EUR_EXCH_RATE AS EUR_EXCH_RATE,
tmp.GBP_EXCH_RATE AS GBP_EXCH_RATE
from(
SELECT
WIP_TO_BILL_LOC_AMT as WIP_TO_BILL_LOC_AMT ,
REALIZATION_LOC_AMT AS REALIZATION_LOC_AMT,
NEG_REAL_LOC_AMT AS NEG_REAL_LOC_AMT ,
POS_REAL_LOC_AMT AS POS_REAL_LOC_AMT,
BILL_IN_ADVANCE_LOC_AMT AS BILL_IN_ADVANCE_LOC_AMT ,
CARRY_FORWARD_loc_AMT AS CARRY_FORWARD_LOC_AMT,
bill_to_client_LOC_AMT AS BILL_TO_CLIENT_LOC_AMT ,
REMAIN_WIP_TO_BILL_LOC_AMT AS REMAIN_WIP_TO_BILL_LOC_AMT,
AR_inv_AMT AS AR_INV_AMT,
ar_tax_amt AS AR_TAX_AMT,
(SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
FROM wc_twfs_olb_invoice_history_f
WHERE ((inv_status_type='FIN'AND inv_status_code NOT IN ('COMPLETE','PROCESSED'))
OR (inv_status_type='WS' AND inv_status_code NOT IN ('PRC'))) --COMPLETED
AND to_char((sysdate-5),'YYYYMMDD') between to_char(status_start_dt,'YYYYMMDD') and to_char(status_end_dt,'YYYYMMDD')group by rpad(integration_id,32)) AS BEG_BAL_WKST_NUM ,
(SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
FROM wc_twfs_olb_invoice_history_f
WHERE (inv_status_code='NEW')
AND to_char((sysdate-4),'YYYYMMDD') between to_char(status_start_dt,'YYYYMMDD') and to_char(status_end_dt,'YYYYMMDD')group by rpad(integration_id,32))AS WKST_RECEIVED_NUM ,
(SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
FROM wc_twfs_olb_invoice_history_f
WHERE ((inv_status_type='FIN' and inv_status_code IN ('COMPLETE','PROCESSED'))
OR (inv_status_type='WS' AND inv_status_code IN ('PRC'))) --COMPLETED
AND to_char((sysdate-4),'YYYYMMDD') between to_char((status_start_dt),'YYYYMMDD') and to_char((status_end_dt),'YYYYMMDD')group by rpad(integration_id,32))AS WKST_PROCESSED_NUM ,
(SELECT count(distinct(RPAD(INTEGRATION_ID,32)))
FROM wc_twfs_olb_invoice_history_f
WHERE (inv_status_type='FIN' AND inv_status_code='CANCELLED')
AND to_char((sysdate-4),'YYYYMMDD') between to_char((status_start_dt),'YYYYMMDD') and to_char((status_end_dt),'YYYYMMDD')group by rpad(integration_id,32)) AS WKST_CANCELED_NUM,
DURATION AS DURATION,
NUM_DAYS AS NUM_DAYS,
NUM_HOURS AS NUM_HOURS,
NUM_MINUTES AS NUM_MINUTES,
NUM_SECONDS AS NUM_SECONDS,
lead_project_office_code AS LEAD_PROJECT_OFFICE_CODE,
lead_project_team_code AS LEAD_PROJECT_TEAM_CODE,
org_id AS ORG_ID,
trunc(sysdate-1) AS RPT_DATE,
to_char((sysdate-1),'YYYYMMDD') AS RPT_DATE_WID,
--last_day(a.report_date) mth_end_dt,
LOC_CURR_CODE AS LOCAL_CURR_CODE,
usd_exch_rate AS USD_EXCH_RATE,
eur_exch_rate AS EUR_EXCH_RATE,
gbp_exch_rate AS GBP_EXCH_RATE
FROM Wc_twfs_olb_invoice_history_f
Where
RPT_DT_MCAL_PERIOD_WID =(select max(RPT_DT_MCAL_PERIOD_WID)from Wc_twfs_olb_invoice_history_f))tmp
group by BEG_BAL_WKST_NUM,WKST_RECEIVED_NUM,WKST_PROCESSED_NUM,WKST_CANCELED_NUM,DURATION,NUM_DAYS,NUM_HOURS,NUM_MINUTES,NUM_SECONDS,
LEAD_PROJECT_OFFICE_CODE,LEAD_PROJECT_TEAM_CODE,ORG_ID,RPT_DATE,RPT_DATE_WID,
LOCAL_CURR_CODE,USD_EXCH_RATE,EUR_EXCH_RATE,GBP_EXCH_RATE;
Can you please suggest me what to do next, and what would be the solution to this.
Thanks a lot in advance. please show me some direction.you may want to change it something like
SELECT SUM(Wip_To_Bill_Loc_Amt) AS Wip_To_Bill_Loc_Amt,
SUM(Realization_Loc_Amt) AS Realization_Loc_Amt,
SUM(Neg_Real_Loc_Amt) AS Neg_Real_Loc_Amt,
SUM(Pos_Real_Loc_Amt) AS Pos_Real_Loc_Amt,
SUM(Bill_In_Advance_Loc_Amt) AS Bill_In_Advance_Loc_Amt,
SUM(Carry_Forward_Loc_Amt) AS Carry_Forward_Loc_Amt,
SUM(Bill_To_Client_Loc_Amt) AS Bill_To_Client_Loc_Amt,
SUM(Remain_Wip_To_Bill_Loc_Amt) AS Remain_Wip_To_Bill_Loc_Amt,
SUM(Ar_Inv_Amt) AS Ar_Inv_Amt,
SUM(Ar_Tax_Amt) AS Ar_Tax_Amt,
COUNT(DISTINCT CASE
WHEN ((Inv_Status_Type = 'FIN' AND
Inv_Status_Code NOT IN ('COMPLETE', 'PROCESSED')) OR
(Inv_Status_Type = 'WS' AND Inv_Status_Code NOT IN ('PRC'))) --COMPLETED
AND To_Char((SYSDATE - 5), 'YYYYMMDD') BETWEEN
To_Char(Status_Start_Dt, 'YYYYMMDD') AND
To_Char(Status_End_Dt, 'YYYYMMDD') THEN
Rpad(Integration_Id, 32)
END) AS Beg_Bal_Wkst_Num,
/*(SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
FROM Wc_Twfs_Olb_Invoice_History_f
WHERE ((Inv_Status_Type = 'FIN' AND
Inv_Status_Code NOT IN ('COMPLETE', 'PROCESSED')) OR
(Inv_Status_Type = 'WS' AND Inv_Status_Code NOT IN ('PRC'))) --COMPLETED
AND To_Char((SYSDATE - 5), 'YYYYMMDD') BETWEEN
To_Char(Status_Start_Dt, 'YYYYMMDD') AND
To_Char(Status_End_Dt, 'YYYYMMDD')
GROUP BY Rpad(Integration_Id, 32)) AS Beg_Bal_Wkst_Num,
(SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
FROM Wc_Twfs_Olb_Invoice_History_f
WHERE (Inv_Status_Code = 'NEW')
AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
To_Char(Status_Start_Dt, 'YYYYMMDD') AND
To_Char(Status_End_Dt, 'YYYYMMDD')
GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Received_Num,
(SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
FROM Wc_Twfs_Olb_Invoice_History_f
WHERE ((Inv_Status_Type = 'FIN' AND
Inv_Status_Code IN ('COMPLETE', 'PROCESSED')) OR
(Inv_Status_Type = 'WS' AND Inv_Status_Code IN ('PRC'))) --COMPLETED
AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
To_Char((Status_Start_Dt), 'YYYYMMDD') AND
To_Char((Status_End_Dt), 'YYYYMMDD')
GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Processed_Num,
(SELECT COUNT(DISTINCT(Rpad(Integration_Id, 32)))
FROM Wc_Twfs_Olb_Invoice_History_f
WHERE (Inv_Status_Type = 'FIN' AND Inv_Status_Code = 'CANCELLED')
AND To_Char((SYSDATE - 4), 'YYYYMMDD') BETWEEN
To_Char((Status_Start_Dt), 'YYYYMMDD') AND
To_Char((Status_End_Dt), 'YYYYMMDD')
GROUP BY Rpad(Integration_Id, 32)) AS Wkst_Canceled_Num,*/
Duration AS Duration,
Num_Days AS Num_Days,
Num_Hours AS Num_Hours,
Num_Minutes AS Num_Minutes,
Num_Seconds AS Num_Seconds,
Lead_Project_Office_Code AS Lead_Project_Office_Code,
Lead_Project_Team_Code AS Lead_Project_Team_Code,
Org_Id AS Org_Id,
Trunc(SYSDATE - 1) AS Rpt_Date,
To_Char((SYSDATE - 1), 'YYYYMMDD') AS Rpt_Date_Wid,
--last_day(a.report_date) mth_end_dt,
Loc_Curr_Code AS Local_Curr_Code,
Usd_Exch_Rate AS Usd_Exch_Rate,
Eur_Exch_Rate AS Eur_Exch_Rate,
Gbp_Exch_Rate AS Gbp_Exch_Rate
FROM Wc_Twfs_Olb_Invoice_History_f
WHERE Rpt_Dt_Mcal_Period_Wid =
(SELECT MAX(Rpt_Dt_Mcal_Period_Wid)
FROM Wc_Twfs_Olb_Invoice_History_f)
GROUP BY Beg_Bal_Wkst_Num,
Wkst_Received_Num,
Wkst_Processed_Num,
Wkst_Canceled_Num,
Duration,
Num_Days,
Num_Hours,
Num_Minutes,
Num_Seconds,
Lead_Project_Office_Code,
Lead_Project_Team_Code,
Org_Id,
Rpt_Date,
Rpt_Date_Wid,
Local_Curr_Code,
Usd_Exch_Rate,
Eur_Exch_Rate,
Gbp_Exch_Rate;Edited by: 986006 on Mar 4, 2013 1:08 PM -
Hi All
I'm having the following query and its giving me "single row sub query returns more than one row". I did some research and all i could come across is using IN,ALL,ANY,NOT IN.... with the WHERE clause but not in the CASE statement so can any one please point me in the right direction?
SELECT ROW_NUMBER () OVER (PARTITION BY traffic_sample_id ORDER BY bin_data_id)
AS row_number_1,
COUNT (bin_data_id) OVER (PARTITION BY traffic_sample_id) AS count_1,
(CASE
WHEN days != 2
THEN (SELECT traffic_sample_id
FROM (SELECT ROW_NUMBER () OVER (PARTITION BY traffic_sample_id ORDER BY bin_data_id)
AS rn,
traffic_sample_id
FROM bin_data)
WHERE rn <= 48)
ELSE (SELECT traffic_sample_id
FROM bin_data)
END
) traffic_sample_id
FROM (SELECT ROW_NUMBER () OVER (PARTITION BY t1.traffic_sample_id ORDER BY t1.bin_data_id)
AS ROW_NUMBER,
COUNT (t1.bin_data_id) OVER (PARTITION BY t1.traffic_sample_id)
AS COUNT,
t1.traffic_sample_id, t1.bin_data_id, t1.end_intv_time,
( TO_DATE (t2.end_date, 'mmddyy')
- TO_DATE (t2.start_date, 'mmddyy')
) AS days
FROM bin_data t1, traffic_sample t2
WHERE t1.traffic_sample_id = t2.traffic_sample_id(+))ThanksHi,
One of these two SELECT statements must be bringing back more thean one row:
THEN (SELECT traffic_sample_id
FROM (SELECT ROW_NUMBER () OVER (PARTITION BY traffic_sample_id ORDER BY bin_data_id)
AS rn,
traffic_sample_id
FROM bin_data)
WHERE rn <= 48)
ELSE (SELECT traffic_sample_id
FROM bin_data) -
Single row sub query returns more than one row
This could be simple SQL but I am just so new to ORACLE SQL so posting it for your help. I need to fix a query
select
Edited by: Lucy Discover on Mar 11, 2011 2:09 PMYou didn't match the subquery to the current row of your query. I guess that you don't need the table sheet in the subquery.
So maybe this would work:
select
ID,
SC_NAME,
WEEK_ENDING,
PIN,
(select (t.pin||' '||o.description)
from PROJECT o
where t.pin = o.pin) as id,
MON,
TUE,
WED,
THU,
FRI,
nvl(TOTAL,0) TOTAL,
AD_ID,
NAME,
SAT,
SUN,
APPROVAL
from SHEET t
WHERE UPPER(AD_ID) = UPPER('USER') -
I need to print one query result as a single row
Hi,
I need to print one query result as a single row ,which gives more than one value (of subinventories)and also i would like to print the quantity of that particular subinventory at particular place.Please suggest how can i do this in the report builder?Actually I need to print inventory report with subinventory break up.For that all subinventories of category code AB are taken as single row.Based on that subinventory value Quantity must be printed at that particular place.
For ex
Quantity
Item no Description Subinventory Code AB_Abc AB_Def AB_ghi
1 ***** 12 9
2 ****** 8 5
like that.I am waiting for the reply.Plz its some how urgent.
Thank you, -
Hi Gurus,
I have been using the sq01 query to do complex calculations and have been successful in creating tons of queries. What I am stuck with right now is this situation. I created a query and the result is in multiple rows. Here's what it looks like
Col1 Col2 Col3 Col4 Col5
0014 0.00 12.00 0.00 1.00
0014 20080428 0.00 0.00 0.00
0014 0.00 0.00 5.00 0.00
0014 0.00 0.00 0.00 0.00
Here;s what I want it to look like
Col1 Col2 Col3 Col4 Col5
0014 20080428 12.00 5.00 1.00
Which means i dont want any rows that basically have 0.00 throught and for the key 0014 I want all the data on one single row.
Is there anyway we can do it using sq01.
Any suggestions will be appreciated. Thanks in advance
Kavita
Edited by: Kavita on Feb 18, 2009 7:44 PMHi,
Its not possible to have in single row.
this is same like Education infotype ,all the qualifications will show in different rows.
You wont get it in single row.
Bu try to Check Qucikviewer and join conditions...that might helpful to get it... -
Outputting Results in a single row from a Table
Afternoon folks,
I have a scenario in hand and I was hoping to get some pointers. I could write a PL/SQL program and all would be fine. I was hoping if there was a way to do it in SQL and not have to create a whole new sub-program for this. I already have a PL/SQL program that populates a table. I want to use that data now and output it in a certain manner.
Any help is greatly appreciated and this is not something I need to solve by tonight. :)
Script to create table and insert records into it:
drop table FLIGHT_ROUTES;
CREATE TABLE FLIGHT_ROUTES
(FLIGHT_NO VARCHAR2(7),
ROUTE_ID NUMBER,
DAY_OF_OPERATION NUMBER,
ORIGIN VARCHAR2(3),
DESTINATION VARCHAR2(3),
STOPVER VARCHAR2(3),
ROUTE_TYPE VARCHAR2(1)
REM INSERTING into FLIGHT_ROUTES
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-1001',1,1,'SFO','LAX',null,'D');
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-1001',1,2,'SFO','LAX',null,'R'); -- Record 2
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-2001',2,1,'SFO','JFK',null,'D');
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-2001',2,2,'SFO','JFK','ORD','D');
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-2001',2,3,'SFO','JFK','DEN','R'); -- Record 5
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-3001',3,1,'LAX','JFK','YYZ','D');
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-3001',3,2,'LAX','JFK','YYC','D');
Insert into FLIGHT_ROUTES (FLIGHT_NO,ROUTE_ID,DAY_OF_OPERATION,ORIGIN,DESTINATION,STOPVER,ROUTE_TYPE) values ('UX-3001',3,3,'LAX','JFK','YUL','D');What I would like to do is output the results by Flight Number, Origin1, Destination1, Origin2, Destination 2 and Origin 3, Destination 3. The maxium number combinations per Flight is 3. The other condition is that the listing should only show the Origin and Destinations and Stopover if it's a Day time Flight. If its a Red Eye, then don't show that option. So, Record 2 would be completely omitted here as it's a Red Eye flight and Record 5 would be omitted for Origin/Destination/Stopover 3 for flight UX-2001.
Flight_No Origin1 Destination1 Stopover 1 Origin2 Destination2 Stopver2 Origin3 Destination3 Stopover3
============================================================================================================================================================
UX-1001 SFO LAX
UX-2001 SFO JFK SFO JFK ORD
UX-3001 LAX JFK YYZ LAX JFK YYC LAX JFK YULEdited by: Roxyrollers on Sep 9, 2011 3:59 PM
Edited by: Roxyrollers on Sep 9, 2011 3:59 PM
Edited by: Roxyrollers on Sep 9, 2011 4:00 PMHi,
Assuming that day_of_operation is what determines whether a row is 1, 2 or 3:
WITH got_r_num AS
SELECT f.*
, ROW_NUMBER () OVER ( PARTITION BY flight_no
ORDER BY day_of_operation
) AS r_num
FROM flight_routes f
WHERE route_type != 'R'
SELECT flight_no || ',' ||
MAX (CASE WHEN r_num = 1 THEN origin END) || ',' || -- Origin 1
MAX (CASE WHEN r_num = 1 THEN destination END) || ',' || -- Destination 1
MAX (CASE WHEN r_num = 1 THEN stopver END) || ',' || -- Stopover 1
MAX (CASE WHEN r_num = 2 THEN origin END) || ',' || -- Origin 2
MAX (CASE WHEN r_num = 2 THEN destination END) || ',' || -- Destination 2
MAX (CASE WHEN r_num = 2 THEN stopver END) || ',' || -- Stopover 2
MAX (CASE WHEN r_num = 3 THEN origin END) || ',' || -- Origin 3
MAX (CASE WHEN r_num = 3 THEN destination END) || ',' || -- Destination 3
MAX (CASE WHEN r_num = 3 THEN stopver END) AS csv_text -- Stopover 3
FROM got_r_num
GROUP BY flight_no
ORDER BY flight_no
;Output:
CSV_TEXT
UX-1001,SFO,LAX,,,,,,,
UX-2001,SFO,JFK,,SFO,JFK,ORD,,,
UX-3001,LAX,JFK,YYZ,LAX,JFK,YYC,LAX,JFK,YULThis does not assume that origin1 is always on the same row with day_of_operation=1. Origin1 will be from the row with the lowest day_of_operation, not counting red-eyes. Likewise, origin2 will be from the row with the 2nd lowest day_of_operation, whether that value is 2 or not.
If your data is such that the row with day_of_operation=n will necessarily be the nth lowest one, not counting red-eyes, then you don't need the sub-query got_r_num; just use your real table (with the condition WHERE route_type != 'R'), and use day_of_operation where I used r_num. (This is what Solomon's solution, which I just saw, does.)
Edited by: Frank Kulash on Sep 9, 2011 4:47 PM
Edited by: Frank Kulash on Sep 9, 2011 4:53 PM -
Merging two results into a single row
Hi, Everyone... I think this is a weighted question and I feel like it's a bit difficult to phrase, so if it doesn't make sense - let me know and I'll try to clarify or provide some more concrete examples (if I can) :)
I have a few tables inner joined in my sql query - I'd post the entire query here but it's lengthy and will probably add a bit more confusion so let's start with theorizing - where the results sometimes generate more than one row. If more than one row exists, I'd like to take the lowest number in one field and the highest number in another field, and display them on a single row.
For instance, when I join the PERIOD and SCHEDULE tables, the PERIOD table might provide two rows like the following:
SCHEDULE_ID PERIOD_ID START_TIME END_TIME
123 100 32820 35640
123 101 35940 38760My final result should take the lowest START_TIME and the highest END_TIME, even if they exist is separate rows.
START_TIME END_TIME
32820 38760It doesn't seem easy to me so if someone can make sense of this - you deserve an award. :) If I can provide some more clarification, please let me know. Thanks for any help. Oracle 11g
Edited by: nage62587 on Sep 27, 2012 11:32 AMnage62587 wrote:
Thanks! I'll try that... I have more than these columns in the result and I'm thinking a Group By likely wouldn't work - I will try but in the event it doesn't, does anyone else have any other suggestions?Group by is the correct way to do this. You group several rows of output into one row. Then you decide which values from inside that group you want to see. This is certainly possible. There are more aggregation functions available than you might think, not only min/max, also min/max + KEEP, count(case expression) and so on. -
How to write multi row sub query with the row containing range of values?
Hi all,
I have to include a column which contains weight ranges and it should come fom table called "report_range_parameters"
The following query will reutrn those weight ranges.
select report_parameter_min_value || ' -> ' || report_parameter_max_value
from report_range_parameters
WHERE report_range_parameters.report_parameter_id = 2359
and report_range_parameters.report_parameter_group = 'GVW_GROUP'
and report_range_parameters.report_parameter_name = 'GVW_NAME'
The below query should return the values group by those weight ranges.
How could I write that sub query?
select SUM(NVL("Class 0", 0)) "Class 0" ,
SUM(NVL("Class 1", 0)) "Class 1" ,
SUM(NVL("Class 2", 0)) "Class 2" ,
SUM(NVL(" ", 0)) "Total"
FROM (
SELECT report_data.bin_start_date_time start_date_time,
SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
SUM(NVL(report_data.gvw_count, 0)) " "
FROM report_data
GROUP BY report_data.bin_start_date_time
) results
RIGHT OUTER JOIN tmp_bin_periods
ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
AND results.start_date_time < tmp_bin_periods.bin_end_date_time
GROUP BY tmp_bin_periods.bin_start_date_time,
tmp_bin_periods.bin_end_date_time Thanks.
Edited by: user10641405 on Jun 15, 2009 3:14 PM
Edited by: user10641405 on Jun 15, 2009 3:17 PMHi,
Assuming the following 4 things:
(1) report_range_parameters contains data like this, from your [previous thread|http://forums.oracle.com/forums/message.jspa?messageID=3541079#3541079]
id group name min_value max_value
1 gvw_group gvw_name 0 5
2 gvw_group gvw_name 5 10
3 gvw_group gvw_name 10 15(2) max_value is actually outside the range (that is, a value of exactly 5.000 is counted in the '5->10' range, not the '0->5' range)
(3) the range has to match some column x that is in one of the tables in your main query
(4) You want to add that column x to the GROUP BY clause
then you shopuld do somehting like this:
select SUM(NVL("Class 0", 0)) "Class 0" ,
SUM(NVL("Class 1", 0)) "Class 1" ,
SUM(NVL("Class 2", 0)) "Class 2" ,
SUM(NVL(" ", 0)) "Total"
, report_parameter_min_value || ' -> ' || report_parameter_max_value AS weight_range -- New
FROM (
SELECT report_data.bin_start_date_time start_date_time,
SUM(DECODE(report_data.gvw, 0, report_data.gvw_count, 0)) "Class 0" ,
SUM(DECODE(report_data.gvw, 1, report_data.gvw_count, 0)) "Class 1" ,
SUM(DECODE(report_data.gvw, 2, report_data.gvw_count, 0)) "Class 2" ,
SUM(NVL(report_data.gvw_count, 0)) " "
FROM report_data
GROUP BY report_data.bin_start_date_time
) results
RIGHT OUTER JOIN tmp_bin_periods
ON results.start_date_time >= tmp_bin_periods.bin_start_date_time
AND results.start_date_time < tmp_bin_periods.bin_end_date_time
LEFT OUTER JOIN report_range_parameters -- New
ON x >= report_parameter_min_value -- New
AND x < report_parameter_max_value -- New
AND report_range_parameters.report_parameter_id = 2359 -- New
and report_range_parameters.report_parameter_group = 'GVW_GROUP' -- New
and report_range_parameters.report_parameter_name = 'GVW_NAME' -- New
GROUP BY tmp_bin_periods.bin_start_date_time,
tmp_bin_periods.bin_end_date_time
, x -- New -
Multi-row sub query returns ORA-00904 :invalid identifier error
I am creating a report from two tables that I am not joining. I want a single line for every row in table1 that meets a date range. Table2 can contain none or many rows for each recored in table1. I want to get up to two fields from table2.
I was using a case statement to check if there was data and then an in-line query or subquery. Once again, the idea is to have a single line on the report for each table1 record.
I get this error with the code below. It seems the nested multi-row subquery can not see the a.cr_mas_cr_no identifier.
ORA-00904: "a"."cr_mas_cr_no": invalid identifier
Any help is greatly appreciated,
Sam
select
a.cr_mas_cr_no "CRNO", a.cr_mas_type "TYPE", a.cr_mas_status "CR Status",
a.cr_mas_date_logged "Logged date", a.CR_REL_REQ_APP_DATE "RTP approved",a.CR_REL_REQ_RTP_DATE "RTP Date",
a.cr_accepted_date "Complete", a.cr_mas_submitted_by "Requester",
select doc_user FROM crrm_cr_documents WHERE doc_cr_number =a.cr_mas_cr_no and rownum = 1 and DOC_TYPE = 'BD' ) "Bus Design",
(select doc_user FROM crrm_cr_documents WHERE doc_cr_number = a.cr_mas_cr_no and rownum = 1 and DOC_TYPE = 'TD' ) "Tech Design",
(select doc_user FROM crrm_cr_documents WHERE doc_cr_number = a.cr_mas_cr_no and rownum = 1 and DOC_TYPE = 'TE' ) "User acceptance test",
case
when (select count(appr_user) from crrm_cr_approvals where appr_cr_no = a.cr_mas_cr_no and appr_type = 'RTP') > 0
then (select appr_user from (select * from crrm_cr_approvals where appr_cr_no = a.cr_mas_cr_no and appr_type = 'RTP') where rownum = 1)
end
"RTP #1",
case
when (select count(appr_user) from crrm_cr_approvals where appr_cr_no = a.cr_mas_cr_no and appr_type = 'RTP') > 1
then (select appr_user from (select * from crrm_cr_approvals where appr_cr_no = a.cr_mas_cr_no and appr_type = 'RTP') where rownum = 2)
end
"RTP #2",
a.CR_REL_REQ_RTP_BY "Released by",
a.CR_ACCEPTED_BY "Post RTP User Acceptance",
a.cr_mas_title "Title", a.cr_mas_id "ID"
from
crrm_crmaster a
where
(a.CR_REL_REQ_RTP_DATE >= :P1109_BEGDATE and (a.CR_REL_REQ_RTP_DATE <= :P1109_ENDDATE) and
(a.cr_mas_status = 'Complete' or (a.cr_mas_status = 'Release Approved'and a.CR_REL_REQ_APP_DATE < :P1109_ENDDATE))
Message was edited by:
slavanawayIceman,
Thanks for the reply I will try your suggestion.
I will try and explain why I think two subqueries (an in-line query with a subquery?) are required. I will use the creation of the column RTP #1 as the example as the RTP #2 column is only different in the rownum selected.
Looking only at the lines that fail, here is my analysis. (If I rem out the two case lines the query runs, I just don't get two columns of data I need.) I will only examine the first case as the second is changed to extract the second approval via the rownum = 2 criteria. The first statement checks there is at least one RTP approval stored for the request and then gets the user who approved the request if the test is true.
case when
(select count(appr_user) from crrm_cr_approvals where appr_cr_no =a.cr_mas_cr_no and appr_type = 'RTP') > 0
then
The above part works fine and the correct count of approvals is returned.
(select appr_user from (select * from crrm_cr_approvals where appr_cr_no=a.cr_mas_cr_no and appr_type = 'RTP') where rownum = 1)
end
"RTP #1",
I moved the parenthesis to the correct location. There can be multiple approvals for a given parent record. Some parent records need one, some need two approvals. If I replace
(select appr_user from (select * from crrm_cr_approvals where appr_cr_no =a.cr_mas_cr_no and appr_type = 'RTP') where rownum = 1)
with
(select appr_user from approvals where appr_cr_no =a.cr_mas_cr_no and appr_type = 'RTP' and rownum = 1)
The correct result is returned because it returns exactly one row as rownum=1 limits the query. When rownum = 2 then the query returns null as the rownum never gets to two as the rownum column is built via the set created by the second subquery.
The subquery builds a set of approvals for a specific "cr_no" and appr_type of "RTP". the outer query then looks at the rownum of the second query
Here is where I got the rownum information from;
http://www.oracle.com/technology/oramag/oracle/06-sep/o56asktom.html
So here is what I think is happening;
1. Main query From and Where are processed. This should provide the "set" for the query
2.The from subqueries for RTP #1 and RTP #2 should be able to access the a.cr_mas_cr_no field and build a set from the approvals table.
3.The RTP #1/2 subquery (inline maybe a better description?) would then get the correct row from the from subquery.
The error "invalid identifier" refers to the a.cr_mas_cr_no field. I assume it means it can not resolve the table alias inside the subquery.
So maybe your grouping would help, I will try.
Sam -
How to display a 1 to many query result in a single row?
Hi,
I want to display a 1 to many relationship in a query in just one row. The current result is that I get more than 1 rows. How can I display it in one column with the additional attribute in a column, without repeating? Thank you.
Select s.student, t.teacher from student_table s, teacher_table t where s.id = t.student_id
Result
Student Teacher
John Doe Larry Woe
John Doe Mary Moe
I would rather get a result like this:
Result
Student Teacher 1 Teacher 2
John Doe Larry Woe Mary Woe
Edited by: Samantha on May 18, 2011 2:48 PMHi,
Will all Students have exactly two Teachers?
If not picture your sample with two more Students.
One having 1 Teacher
One having N Teachers
Think about N, what will it be? - How would you create a table with N columns?
If you can't easily answer above, re-consider what you are trying.
That said, it could still be done - even if all Students do not have exactly two Teachers - and is called Pivot a dynamic number of columns.
Examples are in FAQ
SQL and PL/SQL FAQ
Still a bad idea, with or without known number of teachers
Regards
Peter -
Function to concatenate all query results in a single row comma separeted
Hi All,
my version is Oracle 10.2.0.4.0
this is my query:
select distinct
table1.id
from table1,
table2,
table3
where table1.id = table2.id
and table2.id = table3.id
and table3.id = '761'
and result is:
61
18
68B
S05
S18
68
could someone provide me a function (or something else) in order to have a result like this:
61,18,68B,S05,S18,68
and call it from another query?
I appreciate your help.
Many thanks.
Alessandrouser12889282 wrote:
could someone provide me a function (or something else) in order to have a result like this:
61,18,68B,S05,S18,68
and call it from another query?But this is the wrong way to do it. Better use the original query as a subquery for your second query.
let me demonstrate it
select *
from someotherTable x
where x.FK_ID IN (select t1.id
from table1 t1
table2 t2,
table3 t3
where t1.id = t2.id
and t2.id = t3.id
and t3.id = 761 /* use numbers not strings for IDs! */
;Edited by: Sven W. on Jul 30, 2010 10:17 AM -
Template:Multiple field result in a single row, comma separated
Hello,
without* having to write a function in Pl/SQL, is it possible, when I have this query,
select
"DOSSIER"."ID" as "DOSSIERID",
"DOSSIER"."TITLE" as "TITLE",
"DVD"."ID" as "DVDID",
"DVD"."NAME" as "DVDNAME",
"DVD"."ID_DOSSIER" as "DVD_ID_DOSSIER",
"ELEMENTS"."ID" as "ELEMENTSID",
"ELEMENTS"."NAME" as "ELEMENTSNAME",
"ELEMENTS"."ID_DVD" as "ELEMENTS_ID_DVD"
from "DOSSIER" "DOSSIER",
"DVD" "DVD",
"ELEMENTS" "ELEMENTS"
where "DVD"."ID_DOSSIER"="DOSSIER"."ID"
and "ELEMENTS"."ID_DVD"="DVD"."ID"
and "DOSSIER"."TITLE" = 'FIGARO'**Instead of having this result ( with break in the template)*
FIGARO C2008-203 12l10201.tif
12l10202.tif
12l11101.tif
12l11102.tif
12l11201.tif
12l11202.tif
12l12101.tif
12l12102.tif
C2008-204 12l12202.tif
12l13101.tif
12l13102.tif
12l13201.tif
12l13202.tif
12l14101.tif
12l14102.tif
12l14201.tif
12l14202.tif
12l15101.tif
12l15102.tif
12l15201.tif
C2008-205 12l15202.tif
12l16101.tif
12l16102.tif
12l16201.tif
12l16202.tif
12m01101.tif
12m01102.tifhaving this result, WITH the element only, comma separeted??? ( I can have from 0 to 500 elements)
FIGARO
DVD: C2008-203
Elements: 12l10201.tif, 12l10202.tif, 12l11101.tif, 12l11102.tif, 12l11201.tif, 2l11202.tif, 12l12101.tif, 12l12102.tifthanks, RoselineThis should help you http://tkyte.blogspot.com/2007/03/stringing-them-up.html
-
How to avoid word wrap in the BW Report so that result fits in single row
Hello Colleagues
I have a report which shows Material number versus Revenue. In the row, material is displayed with Technical name and description.
Here, the view of the report shows the description in single line. While, in the report, description of the report runs 3 to 4 lines though description contains 5 to 6 words (which can fit easily into single line).
Let me know how to restrict each row descrption into single line.
Regards,
Ningarajuno answers opened new thread to make more clear
-
Single row subquery Returning more than one row
Hi,
This is urgent.............
could u any one please suggest me on this query it returning single row subquey returnin more than one row
In this 2nd suquery fails some of the order_numbers returning more than price_list based on dates and in that situvation also my query has to successfull
fro that i added this condition l.ordered_quantity between trunc(product_attr_value_from) and (product_attr_value_to) for that condition also failing this query
pls give me the correct condition to approach this solution
select
substr(party.party_name,1,13),
c.account_number,
substr(h.order_number||'-'||l.line_number||'-'||l.shipment_number,1,15),
q.name,l.unit_selling_price,
(select qll.operand
apps.qp_list_headers qlh,
apps.qp_list_lines qll,
apps.qp_list_lines qllx
apps.qp_pricing_attributes qpa,
apps.qp_rltd_modifiers qrm,
apps.mtl_system_items msi
wherer qll.list_header_id=qlh.list_header_id
and qpa.list_header_id=qlh.list_header_id
and qpa.list_line_id=qll.list_line_id
and qrm.rltd_modifier_grp_type='PRICE BREAK'
and qll.list_line_id=qrm.to_rltd_modifier_id
and qll.list_line_type_code='PLL'
and qllx.list_header_id=qlh.lsit_header_id
and qllx.list_line_id=qrm.from_rltd_modifier_id
and qllx.list_line_type_code='PBH'
and qlh.list_header_id=l.price_list_id
and qpa.product_attr_value=msi.inventory_item_id
and qpa.product_attr_value=l.inventory_item_id
and msi.segment2 is null
and msi.organization_id=89
and trunc(l.request_date) between trunc(qllx.start_date_active) and trunc(nvl(qllx.end_date_active,sysdate))
and l_ordered_quantity between qpa.pricing_attr_value_from and qpa.pricing_attr_value_to
and qpa.product_uom_code=l.pricing_quantity_uom),
substr(l.ordered_item,1,13),
u.user_name,
t.name,
l.ordered_quantity,
l.creation_date,
l.request_date,
l.pricing_date,
l.flow_status_code
from apps.oe_order_headers_all h,
hz_cust_Accounts c,
hz_parties party,
apps.oe_order_lines_all l,
apps.qp_list_headers_tl q,
apps.qp_list_headers_b qb,
apps.fnd_user u,
apps.so_order_types_all t
where h.header_id=l.header_id
and h.sold_to_org_id=c.cust_account_id
and c.party_id=party.party_id
and trunc(l.request_date)!=trunc(l.pricing_date)
and qb.attribute1='Q'
and q.list_header_id=qb.list_header_id
and l.price_list_id=q.list_header_id
and l.flow_status_code=!='CANCELLED'
AND t.name!='ECOM'
and t.name!='RMA'
and l.open_flag='Y'
and l.item_type_code='MODEL'
and u.user_id=l.created_by
and t.order_type_id=h.order_type_id
and u.user_name='XXCONVERSION'
and (l.unit_selling_price -
(select qll.operand
from apps.qp_list_headers qlh,
apps.qp_lsit_lines qll,
apps.qp_list_lines qllx,
apps.qp_pricing_attributes qpa,
apps.qp_rltd_modifiers qrm,
apps.mtl_system_items msi
where qll.list_header_id=qlh.list_header_id
and qpa.list_header_id=qlh.lsit_header_id
and qpa.list_line_id=qll.list_line_id
and qrm.rltd_modifier_grp_type='PRICE BREAK'
AND qll.list_line_id=qrm.to_rltd_modifier_id
and qll.list_line_type_code='PLL'
and qllx.list_header_id=qlh.list_header_id
and qllx.list_line_id=qrm.from_rltd_modifier_id
and qllx.list_line_type_code='PBH'
and qlh.list_header_id=l.price_list_id
and qpa.product_attr_value=msi.inventory_item_id
and qpa.product_Attr_value=l.inventory_item_id
and msi.segmetn2 is null
and msi.organization_id=89
trunc(l.request_date) between trunc(qllx.start_date_active) and trunc(nvl(qllx.end_date_active,sysdate)) and
and l.ordered_quantity between qpa.pricing_attr_value_from and qpa.pricing_attr_value_to
and qpa.product_uom_code=l.pricing_quantity_uom)!=0)
order by creation_dateHi,
995631 wrote:
Hi,
This is urgent.............Then don't use this forum.
could u any one please suggest me on this query it returning single row subquey returnin more than one row
In this 2nd suquery fails some of the order_numbers returning more than price_list based on dates and in that situvation also my query has to successfullRemember, none of the people who want to help you are as familiar with your application as you are, so you have to explain things that are obvious to you.
What does "sucessful" mean in this case? Does is mean producing the right results? What are the right results? How can you tell them apart from the wrong results?
As the errror message says, the (immediate) problem is that a single-row sub-query is returning more than a single row. If the sub-query tries to bring back more than 1 row, which one do you want to use? Or do you want to use some kind of aggregate, such as the average, which might not be the same as any of them?
Whenever you have a problem, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all the tables involved, and the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Simplify the problem as much as possible. For example, remove all columns and tables that have nothing to do with the part you don't know how to do.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Maybe you are looking for
-
How to execute custom code only when a specific node is selected in infoset
Hi, We have written a piece of custom code under a node (P1045). Not all users will have access to this Infotype as it is related to Appraisals. So, when users (w/no access to 1045) try to run a Query for other info types data, they are getting error
-
During the syncing of ios5 I lost an important app that was inside another app called productivity. Is it possible to retrieve this?
-
HT4972 i have just updated my 3S and it has failed to activate. what can i do?
i have just updated my 3S and it has failed to activate. what can i do?
-
Session variable usage in report title
Is there a way to add session variable s_x in the report's title text? What is the correct syntax?
-
Rotate Plot Legend of XY graph
Is it possible to rotate the plot legend so the letters of the plot names run from bottom to the top rather than across the operator interface? The names for my plots are bigger and I need to show at least four plots at the same time. Putting scales