Grouping by a single column of select statement to set status
Hi,
I need a help in getting the o/p in a single SQL statement.
I have the below scenario:
Part_No Event Indic --Status
A E1 X
A E2 Y
A E3 N --Null
B C1 Y
B C2 Y
B C3 Y --Listed
C D1 Null
C D2 Y
C D3 Y ---Unknown
I need to derive the status as shown above:
1. "Listed" when all Events has Indic as Y
2. "Unlisted" when atleast one Event has Indic as N
3. "Unknown" when atleast one Event has X or Null
I wanted the result like given below:
Part_No Status
A Null
B Listed
C Unknown
Please help me get this in a single SQL statment
Thanks
SaintelE
Hi,
Please let me know if the below is elaborative:
I need a help in setting the status based on the values given below in a table.
Say for example, I have the below rows in a table : column names: Part_No, Event, Indic
I need to derive the Status as "Unlisted", "Listed", "Unknown" using Case statement:
Part_No Event Indic --Status
A E1 X
A E2 Y
A E3 N --Unlisted
B C1 Y
B C2 Y
B C3 Y --Listed
C D1 Null
C D2 Y
C D3 Y --Unknown
I need to derive the Status value as
1. "Listed" only when all Events (E1, E2, E3) has Indic as Y,
2. "Unlisted" only when atleast one Event has Indic as N
3. "Unknown" only when atleast one Event has "X" or Null
I wanted the result like given below by grouping by Part_No:
Part_No Status
A Null
B Listed
C Unknown
Please help me get this in a single SELECT statment
Thanks
SaintelE
Similar Messages
-
SQL column as select statement to be referenced into a group by
Is there a notation or solution to be able to reference a column that is a inline select statement within a group by as detailed below? The group by will not accept the alias. I also tried to make the SQL a MAX to remove the need for the group by reference and this returned invalid expression.
SELECT DISTINCT hdr.BUSINESS_UNIT,
hdr.SESSN_ID,
hdr.STREAM_ROOT_ID,
hdr.SESSN_STS_CD,
hdr.SESSN_CRE_DTTM,
CASE
WHEN C.OPRID <> ' ' THEN C.OPRID
ELSE S.OPERATOR
END OPRID,
strm.QS_APP_CONTEXT,
RECV.QTY_SH_RECVD Quantity_Received,
CASE
WHEN hdr.BUSINESS_UNIT = 'MFG01' THEN MAX(G.MFDS_SGRP_SIZE)
ELSE MAX(S.SESSN_SGRP_SIZE)
END Quantity_Inspected,
MAX(S.QS_VALUEREADING_1) Defect_Count,
CASE
WHEN MAX(S.QS_VALUEREADING_1) = 0 THEN ' '
ELSE MAX(G.MFDS_NAME)
END Characteristic,
MAX(CMNT.QS_COMMENT2) COMMENTS,
strm.INV_ITEM_ID,
itm.DESCR,
strm.WORK_CENTER_CODE,
strm.VENDOR_ID,
*(SELECT V.NAME1 FROM PS_VENDOR V WHERE strm.VENDOR_ID = V.VENDOR_ID AND V.SETID = (SELECT SETID FROM PS_SET_CNTRL_REC*
WHERE RECNAME = 'VENDOR'
AND SETCNTRLVALUE = strm.BUSINESS_UNIT)) VENDOR_NAME,
strm.PRDN_AREA_CODE,
strm.COMPL_OP_SEQ,
strm.PRODUCTION_TYPE,
C.RECEIVER_ID,
C.RECV_LN_NBR,
RECV.PO_ID,
RECV.LINE_NBR,
RECV.SCHED_NBR,
C.PRODUCTION_ID,
C.SERIAL_ID,
C.INV_LOT_ID
FROM PS_QS_SESSN_HDR8 hdr
LEFT OUTER JOIN PS_QS_SESSN_TRACE8 C
ON hdr.BUSINESS_UNIT = C.BUSINESS_UNIT
AND hdr.SESSN_ID = C.SESSN_ID
LEFT OUTER JOIN PS_RECV_INSPDTL_VW RECV
ON C.BUSINESS_UNIT = RECV.BUSINESS_UNIT
AND C.RECEIVER_ID = RECV.RECEIVER_ID
AND C.RECV_LN_NBR = RECV.RECV_LN_NBR
LEFT OUTER JOIN PS_QS_STREAM_ROOT strm
ON hdr.STREAM_ROOT_ID = strm.STREAM_ROOT_ID
AND hdr.BUSINESS_UNIT = strm.BUSINESS_UNIT
LEFT OUTER JOIN PS_QS_STREAM8_VW G
ON strm.STREAM_ROOT_ID = G.STREAM_ROOT_ID
AND strm.BUSINESS_UNIT = G.BUSINESS_UNIT
LEFT OUTER JOIN PS_QS_SUBGROUP S
ON hdr.BUSINESS_UNIT = S.BUSINESS_UNIT
AND hdr.SESSN_ID = S.SESSN_ID
AND S.STREAM_ID = G.STREAM_ID
LEFT OUTER JOIN PS_QS_SESSN_COMM8 CMNT
ON S.BUSINESS_UNIT = CMNT.BUSINESS_UNIT
AND S.SESSN_ID = CMNT.SESSN_ID
AND S.STREAM_ID = CMNT.STREAM_ID
AND C.SAMPLE = CMNT.SAMPLE
LEFT OUTER JOIN PS_MASTER_ITEM_TBL itm
ON itm.INV_ITEM_ID = strm.INV_ITEM_ID
LEFT OUTER JOIN PS_SET_CNTRL_REC cntrl
ON itm.SETID = cntrl.SETID
AND cntrl.RECNAME = 'MASTER_ITEM_TBL'
AND cntrl.SETCNTRLVALUE = strm.BUSINESS_UNIT
WHERE S.QS_VALUEREADING_1 = (SELECT MAX(S2.QS_VALUEREADING_1)
FROM PS_QS_SUBGROUP S2
WHERE S2.BUSINESS_UNIT = S.BUSINESS_UNIT
AND S2.SESSN_ID = S.SESSN_ID
AND S2.STREAM_ID = S.STREAM_ID)
GROUP BY hdr.BUSINESS_UNIT,
hdr.SESSN_ID,
hdr.STREAM_ROOT_ID,
hdr.SESSN_STS_CD,
hdr.SESSN_CRE_DTTM,
C.OPRID,
S.OPERATOR,
strm.QS_APP_CONTEXT,
RECV.QTY_SH_RECVD,
strm.INV_ITEM_ID,
itm.DESCR,
strm.WORK_CENTER_CODE,
strm.VENDOR_ID,
VENDOR_NAME,
strm.PRDN_AREA_CODE,
strm.COMPL_OP_SEQ,
strm.PRODUCTION_TYPE,
C.RECEIVER_ID,
C.RECV_LN_NBR,
RECV.PO_ID,
RECV.LINE_NBR,
RECV.SCHED_NBR,
C.PRODUCTION_ID,
C.SERIAL_ID,
C.INV_LOT_IDHi,
Assign the alias in a sub-query. Then you'll be able to use it wherever you want to, and how many times you want to, in a super-query.
For example:
WITH got_vendor AS
SELECT hdr.business_unit
SELECT v.name1
FROM ps_vendor v
WHERE strm.vendor_id = v.vendor_id
AND v.setid = (
SELECT setid
FROM ps_set_cntrl_rec
WHERE recname = 'VENDOR'
AND setcntrlvalue = strm.business_unit
) AS vendor_name
FROM ps_qs_sessn_hdr8 hdr
SELECT business_unit -- NOTE: no hdr.; all columns are from got_vendor now
, vendor
FROM got_vendor
GROUP BY business_unit
, vendor
;When you define an alias (such as vendor) in a query, you can use that alias in the ORDER BY clause of that same query, but that's the only place in that same query where you can use it. If you want to use the alias anywhere else (e.g., in the GROUP BY clause, as in your example, the WHERE clause, or elsewhere in the SELECT clause), then you probably want to compute it in a sub-query, as shown above.
There's probably a better way to compute vendor, but that's a separate problem.
Edited by: Frank Kulash on Jan 3, 2012 10:37 AM
Added example -
Retrieving multiple values from one column in SELECT statement
Hi,
I have a slight dilemma in that I'm trying to pull down all the values from a column from a select statement that includes some JOINS in it.
If I run the query at the SQL Plus prompt, it pulls back all the values/rows.
When I run the select (and prepared ) statement in my JSP, it only pulls back one of the 4 values I'm trying to retrieve.
e.g.
at the DB level :
SELECT role_name, CC_ID FROM votetbl a
INNER JOIN APPROVERS b ON
a.BUSVP = b.BUSVP AND
a.BRANCH = b.BRANCH
WHERE CC_ID = 1688this will return:
ROLE_NAME CC_ID
ops 1688
ops 1688
comply 1688
legal 1688
comply 1688
When run in my JSP, like so:
String primID3a = request.getParameter("primID");
Statement stmtovoter = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
String prepvotSQL = "SELECT role_name, CC_ID FROM votetbl a INNER JOIN APPROVERS b ON a.BUSVP = b.BUSVP AND " +
"a.BRANCH = b.BRANCH WHERE CC_ID = ?";
PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
prepvotstmt.setString(1, primID3a);
ResultSet rest3 = prepvotstmt.executeQuery();
rest3.next();
String votecat = rest3.getString(1);
out.println("Vote category: "+votecat);I only get ops returned.
Do I need to run an enumerator? Or reqest.getParameterValues or use a while statement around the results set?
Any feedback and direction here is welcomed!
Thanks!Actually, I tried looping and still only get 1, but returned several times.
i.e.
PreparedStatement prepvotstmt = connection.prepareStatement(prepvotSQL);
prepvotstmt.setString(1, primID3a);
ResultSet rest3 = prepvotstmt.executeQuery();
rest3.next();
String votecat = rest3.getString(1);
while (rest3.next()) {
out.print("category roles "+votecat);
}then I get returned the following:
admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admincategory roles admin
like so.
Where as at the DB level I get
ROLE_NAME CC_ID
admin 1688
ops 1688
ops 1688
ops 1688
ops 1688
ops 1688
ops 1688
ops 1688
risk 1688
comply 1688
legal 1688
legal 1688
ops 1688
comply 1688
Maybe the while should go around the getString(1) designation? But I was thinking I'd tried that and gotten invalid cursor error
Something is definitely amiss, between the prepared statement in the servlet and the SELECT statement at the DB level.
I can totally hardcode the statement in the servlet or JSP and it will return one value potentially several times, but only one.
Other times, it will not return a value at all, even though one resides in the db.
Yet go to the DB/SQL Plus prompt and it returns perfectly. I can simply copy and paste the SELECT statement from the out.print line I made and it works like a champ in SQL Plus. Any ideas why the same exact thing cannot return the proper values within the servlet/JSP?
Yeeeeeeesh!!! : (
Message was edited by:
bpropes20 -
How: making column value as column of select statement
Hi
Quickly I have searched in this forum for following solution but not able to find it.
I need to make a query in such a way that the value of one column in one table should act as a column-name of another table
Eg:-
tab1
col1,col2,*col3*,col4
tab2
col11 col22 col33 col44
row1 a b col3 d
row2 aa bb cc dd
So the query should be something like --- in row2 if the value is col3 then from tab1 I should pick the col3 in select statement (basically there will be some join in tab1 and tab2 )
Hope I am able to make u all understand my query.
regardsHi all,
Sorry for late response.Just now I checked all the replies.
Actually I tried in this way.
CREATE OR REPLACE function Proc_caption (in_tan varchar2, in_order in number)
return varchar2
is
d varchar2(100) ;
begin
SELECT col1 into d
from tab1
Where
col2 = in_tanid
AND col3 = 'Y'
AND col4 = in_order ;
return d ;
Exception
WHen No_DATA_FOund then
return 'N' ;
end ;
create or replace procedure proc_generate_view(in_tan varchar2, in_soc varchar2)
is
x varchar2(2000);
v4 varchar2(50) ;
v5 varchar2(50) ;
cnt number ;
begin
v4:= PROC_Caption (in_tan,4) ;
v5:= PROC_Caption (in_tan,5) ;
x := ' Create view v_generate as '
|| ' SELECT a , b, c, d ' ;
if v4 <> 'N' THEN
x := x || ' , ' || PROC_Caption (in_tan,4) || ' as Caption4 ' ;
end if;
if v5 <> 'N' THEN
x := x || ' , ' || PROC_Caption (in_tan,5) || ' as Caption5 ' ;
end if;
x := x || ' FROM tab2 WHERE col1 = ''' || in_socid || ''''
|| ' AND col2 = ''' || in_tan || '''' ;
select count(1) into cnt from USER_OBJECTS where OBJECT_NAME = 'V_GENERATE'
and OBJECT_TYPE = 'VIEW' ;
if cnt > 0 then
EXECUTE IMMEDIATE ' DROP view V_GENERATE' ;
END IF ;
execute immediate x ;
end ;
NOTE:- I have just renamed the table name and column names in order to make it non confedential...
I have created this successfully with actual table name and column names and able to get the result as per my requirement.
regards -
Does the column selected in the select statement will effect the table access. I have a query selecting 10 columns from different tables using joins and inline views. One table is going for a Full table Scan.
When I searched for the cause, I couldn't find anything. Everything looks correct. When I comment 2 two particular columns from the select statement the table is not scanned fully.
Those two columns are not the part of the index. Why does a selection of columns affect the Explain plan?
Thanks,
GMHi Gints,
Thank you for your reply. This is my query and
nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
TICKET_JOIN.TDSOQS QUANTITY_TICKETED are the columns tha's creating issue. If I comment those columns Index is accessed properly.
select
'TKT' SOURCE,
TICKET_JOIN.TKDO01 HIRE_ID,
TICKET_JOIN.TKQ101 TRUCK_ID,
TICKET_JOIN.TKVEHT TRUCK_TYPE,
1 TRUCK_COMM,
nvl(TKCMP1,0) TICKET_NUM,
nvl(TKADTM,0) TICKET_TIME,
--TICKET_JOIN.TDSOQS QUANTITY_TICKETED,
0 CHECKIN_TIME,
--nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
nvl(DDADTM,0) START_TIME
from
(select
TICKET.TKCMP1,
TICKET.TKDO01,
TICKET.TKQ101,
TICKET.TKADTM ,
TICKET.TKVEHT,
TICKET_DETAILS.TDAITM ,
TICKET_DETAILS.TDQRLV ,
TICKET_DETAILS.TDSOQS ,
TICKET.TKCNTF,
TICKET.TKTRDJ,
TICKET.TK58GA8
from
CRPDTA.F5800091 TICKET_DETAILS ,
CRPDTA.F5800090 TICKET
where TICKET.TKCMP1 = TICKET_DETAILS.TDCMP1
and TICKET.TKTRDJ = TICKET_DETAILS.TDTRDJ
and TICKET.TKTRDJ = 107085
and TICKET.TKEV12 <> 'Y'
and TICKET.TK58GA8='ECSEO'
and TICKET.TKCNTF = '11') TICKET_JOIN ,
(select
DDDOCO,
DDCNTF,
DDQTFN,
DDAITM,
DDADTM,
DD58GA8,
DDTRDJ
from
CRPDTA.F5800051 ORDER_DETAILS,
CRPDTA.F5800050 ORDER_HEADER
where
ORDER_HEADER.DHDOCO = ORDER_DETAILS.DDDOCO
and ORDER_HEADER.DHTRDJ = ORDER_DETAILS.DDTRDJ
and ORDER_HEADER.DH58GA8 = ORDER_DETAILS.DD58GA8
and ORDER_HEADER.DHDCTO = ORDER_DETAILS.DDDCTO
/*and
(ORDER_HEADER.DHTRDJ = 107085
OR (ORDER_HEADER.DHTRDJ = 107084 and ORDER_HEADER.DHEV04='Y')
and TRIM(ORDER_HEADER.DH58GA8) = 'ECSEO'
and TRIM(ORDER_DETAILS.DDCNTF) = '11' ) ORDER_VIEW
where TICKET_JOIN.TKTRDJ = ORDER_VIEW.DDTRDJ
and TICKET_JOIN.TDAITM = ORDER_VIEW.DDAITM
and TICKET_JOIN.TKCNTF = ORDER_VIEW.DDCNTF
and TICKET_JOIN.TK58GA8 = ORDER_VIEW.DD58GA8
and NOT EXISTS ( select 1 from CRPDTA.F5800120 TRUCK_ASSIGNMENT
where TATRDJ = 107085
and TACNTF = '11'
and TA58GA8 = 'ECSEO'
and TICKET_JOIN.TKQ101||TICKET_JOIN.TKVEHT = TAQ101||TAVEHT )
Thanks
GM -
Adding columns in select statements
All if i have the following statement and i wanted to add the two volume columns in the select statement can i just do a A1.volume + A2.Volume as vol
SELECT A1.ORDERID,A1.MARKET,A1.GIMSG, A2.ORDERID,A2.MARKET,A2.TRADERID, A1.VOLUME, A2.VOLUME
FROM table1 A1 JOIN table2
ON A1.TRADEDATE = A2.TRADEDATENo that wouldnt work,
Error will be invalid no(error no ORA-01722)
but you can use pipe(||)
select col1||col2 as col from ......
ex: SQL> select e.ename||d.dname as result_col from emp e,dept d where e.deptno=d.deptno;
RESULT_COL
SMITHRESEARCH
ALLENSALES
WARDSALES
JONESRESEARCH
MARTINSALES
BLAKESALES
CLARKACCOUNTING
SCOTTRESEARCH
KINGACCOUNTING
TURNERSALES
ADAMSRESEARCH
RESULT_COL
JAMESSALES
FORDRESEARCH
MILLERACCOUNTING
14 rows selected.
Message was edited by:
user517498 -
Passing of internal table values to the select statement as SETS
Hi All,
Is there any way that i can restrict the values of a internal table to be passed to a select statement set by set..
say for eg: if a itab has 1000 entries i want the first 500 to be going out in a select statement as a comparision for all entries and then the next set of 500 to go out..
Please let me know.. this is very urgent..<b>Appending Several Lines</b>
You can also append internal tables to index tables using the following statement:
APPEND LINES OF <itab1> TO <itab2>.
This statement appends the whole of ITAB1 to ITAB2. ITAB1 can be any type of table, but its line type must be convertible into the line type of ITAB2.
When you append an index table to another index table, you can specify the lines to be appended as follows:
APPEND LINES OF <itab1> [FROM <n1>] [TO <n 2>] TO <itab2>.
<n 1 > and <n 2 > specify the indexes of the first and last lines of ITAB1 that you want to append to ITAB2.
This method of appending lines of one table to another is about 3 to 4 times faster than appending them line by line in a loop. After the APPEND statement, the system field SY-TABIX contains the index of the last line appended. When you append several lines to a sorted table, you must respect the unique key (if defined), and not violate the sort order. Otherwise, a runtime error will occur.
Then u can use <b> FOR ALL ENTRIES</b> in select query.
regards
vinod -
Sort key too long - maximum number of columns in select statement
the sort key too long is caused by either too many group
functions or too many columns selected. Does anyone know the
maximum number of columns that can be selected in one statement ?The Oracle 9i reference states ...
The GROUP BY expression and all of the
nondistinct aggregates functions (for example,
SUM, AVG) must fit within a single database
block.
... and the Oracle 9i SQL Reference states that ...
An order_by_clause can contain no more than 255
expressions.
You could check your own documentation, but i think it will
be the same. -
Conditional Columns in Select Statement for any type of Report
Okay so I had a requirement to conditionally show columns on a report when the data in the column was not null. I played around the "vertical" report mentioned in other posts but it didn't work well for my needs. Also I know that there is a javascript solution for this as demonstarted in Denes Kubicek's app (which was copied from Vikas :) ). Anyways listed below is my approach.... Hope this can help anyone else out as it's just pl/sql returning sql. Also you will need execute on dbms_sql for this to work.
declare
v_count number := 0;
v_row_count number := 0;
v_col_name varchar2(100);
q varchar2(4000) := 'select ';
v_table_name varchar2(100) := :SOME_TABLE_NAME;
v_id varchar2(100) := 'num = '||:SOME_APEX_VALUE;
my_c INTEGER;
fdbk INTEGER;
statement varchar2(2000);
cval_out varchar2(2000);
nval_out number;
begin
select count(*) into v_count from cols
where table_name = v_table_name;
for counter in 1..v_count
loop
select column_name into v_col_name
from cols where table_name = v_table_name
and counter = column_id;
statement := 'select count(*) '||
' from '||v_table_name||
' where '||v_col_name||' is not null and '||v_id;
my_c := dbms_sql.open_cursor;
dbms_sql.parse(my_c,statement,dbms_sql.native);
dbms_sql.define_column(my_c,1,nval_out);
fdbk := dbms_sql.execute(my_c);
LOOP
exit when dbms_sql.fetch_rows(my_c) = 0;
dbms_sql.column_value(my_c,1,nval_out);
end loop;
v_row_count := nval_out;
dbms_sql.close_cursor(my_c);
if v_row_count > 0 then
q:=q||v_col_name||',';
end if;
end loop;
if(substr(q,length(q),1) = ',') then
q:= substr(q,0,length(q)-1);
end if;
q:= q||' from '||v_table_name||' where '||v_id;
end;Hope this helps...
-David
Message was edited by:
rdpatricHi Gints,
Thank you for your reply. This is my query and
nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
TICKET_JOIN.TDSOQS QUANTITY_TICKETED are the columns tha's creating issue. If I comment those columns Index is accessed properly.
select
'TKT' SOURCE,
TICKET_JOIN.TKDO01 HIRE_ID,
TICKET_JOIN.TKQ101 TRUCK_ID,
TICKET_JOIN.TKVEHT TRUCK_TYPE,
1 TRUCK_COMM,
nvl(TKCMP1,0) TICKET_NUM,
nvl(TKADTM,0) TICKET_TIME,
--TICKET_JOIN.TDSOQS QUANTITY_TICKETED,
0 CHECKIN_TIME,
--nvl(TICKET_JOIN.TDQRLV,0) ACC_SHIPPED_QTY,
nvl(DDADTM,0) START_TIME
from
(select
TICKET.TKCMP1,
TICKET.TKDO01,
TICKET.TKQ101,
TICKET.TKADTM ,
TICKET.TKVEHT,
TICKET_DETAILS.TDAITM ,
TICKET_DETAILS.TDQRLV ,
TICKET_DETAILS.TDSOQS ,
TICKET.TKCNTF,
TICKET.TKTRDJ,
TICKET.TK58GA8
from
CRPDTA.F5800091 TICKET_DETAILS ,
CRPDTA.F5800090 TICKET
where TICKET.TKCMP1 = TICKET_DETAILS.TDCMP1
and TICKET.TKTRDJ = TICKET_DETAILS.TDTRDJ
and TICKET.TKTRDJ = 107085
and TICKET.TKEV12 <> 'Y'
and TICKET.TK58GA8='ECSEO'
and TICKET.TKCNTF = '11') TICKET_JOIN ,
(select
DDDOCO,
DDCNTF,
DDQTFN,
DDAITM,
DDADTM,
DD58GA8,
DDTRDJ
from
CRPDTA.F5800051 ORDER_DETAILS,
CRPDTA.F5800050 ORDER_HEADER
where
ORDER_HEADER.DHDOCO = ORDER_DETAILS.DDDOCO
and ORDER_HEADER.DHTRDJ = ORDER_DETAILS.DDTRDJ
and ORDER_HEADER.DH58GA8 = ORDER_DETAILS.DD58GA8
and ORDER_HEADER.DHDCTO = ORDER_DETAILS.DDDCTO
/*and
(ORDER_HEADER.DHTRDJ = 107085
OR (ORDER_HEADER.DHTRDJ = 107084 and ORDER_HEADER.DHEV04='Y')
and TRIM(ORDER_HEADER.DH58GA8) = 'ECSEO'
and TRIM(ORDER_DETAILS.DDCNTF) = '11' ) ORDER_VIEW
where TICKET_JOIN.TKTRDJ = ORDER_VIEW.DDTRDJ
and TICKET_JOIN.TDAITM = ORDER_VIEW.DDAITM
and TICKET_JOIN.TKCNTF = ORDER_VIEW.DDCNTF
and TICKET_JOIN.TK58GA8 = ORDER_VIEW.DD58GA8
and NOT EXISTS ( select 1 from CRPDTA.F5800120 TRUCK_ASSIGNMENT
where TATRDJ = 107085
and TACNTF = '11'
and TA58GA8 = 'ECSEO'
and TICKET_JOIN.TKQ101||TICKET_JOIN.TKVEHT = TAQ101||TAVEHT )
Thanks
GM -
In Oracle SQL, cannot use column in select statement and order by
Hi,
Is there a work around for this.
Thanks in advance
Pablo.Hi,
943981 wrote:
Hi All,
This is the error I get:
ORA-00960: ambiguous column naming in select list
00960. 00000 - "ambiguous column naming in select list"
*Cause: A column name in the order-by list matches more than one select
list columns.
*Action: Remove duplicate column naming in select list.
Error at Line: 6 Column: 17That error message looks pretty clear to me. What don't you understand?
Either
(a) use aliases, so each column has a unique name, or
(b) remove duplicate columns from the SELECT clause.
Post your query. It's hard to say exactly what you're doing wrong when we don't know exactly what you're doing.
For best results, post a complete test script (including CREATE TABLE and INSERT statements, if necessary) that people can to re-create the problem and test their ideas.
See the forum FAQ {message:id=9360002} -
Leaving out columns in Select statements
Hello! I'm just looking for confirmation on something really for some work I'm doing at uni..
I'm looking to put together a query that can disregard certain columns depending on whats stored in them. E.g, I'm making a football management system.. my results table contains fields for goal scorers (columns for goalone, goaltwo - up to goal ten, etc). Each row for this table is obviously going to have different amounts of goal scorers, e.g. there will be times when goalfour - goalten are null when there are 3 goalscorers. There are also going to be times when I only want to display certain goalscorer names and not other names, so I'll be wanting to disregard columns that contains anyone but Wayne Rooney for example.
What I'm asking therefore is if there is any query that can display a row, but disregard the columns that contain certain values, e.g. Select * from ResultsTable, Ignore where goalone, goaltwo, goalthree, (etc etc) = Null;
I'm currently getting the following results with the queries I'm trying:
COLUMN HEADER: goalone goaltwo goalthree goal four goal five
ROW 1: Rooney Drogba Van Persie NULL NULL
ROW 2: Van Persie NULL NULL NULL NULL
(i.e displaying nulls when, if its possible, I want something like:
COLUMN HEADER: goalone goaltwo goalthree goal four goal five
ROW 1: Rooney Drogba Van Persie
ROW 2: Van Persie
e.g. It will only show goal scorers and not a huge list of Null none scorers.
On reflection there may even be better approaches to storing goal scorers but I'm against time now and i'm hoping there'll be a query to do something like what I want. I've only been able to find queries through Google that look for Nulls and then disregard the whole row if it finds one, which is obviously not what I want!
Any help is hugely appreciated! Thanks! :)Hi,
986500 wrote:
Hello! I'm just looking for confirmation on something really for some work I'm doing at uni..
I'm looking to put together a query that can disregard certain columns depending on whats stored in them. E.g, I'm making a football management system.. my results table contains fields for goal scorers (columns for goalone, goaltwo - up to goal ten, etc). Each row for this table is obviously going to have different amounts of goal scorers, e.g. there will be times when goalfour - goalten are null when there are 3 goalscorers. There are also going to be times when I only want to display certain goalscorer names and not other names, so I'll be wanting to disregard columns that contains anyone but Wayne Rooney for example.
What I'm asking therefore is if there is any query that can display a row, but disregard the columns that contain certain values, e.g. Select * from ResultsTable, Ignore where goalone, goaltwo, goalthree, (etc etc) = Null;
I'm currently getting the following results with the queries I'm trying:
COLUMN HEADER: goalone goaltwo goalthree goal four goal five
ROW 1: Rooney Drogba Van Persie NULL NULL
ROW 2: Van Persie NULL NULL NULL NULLSee the forum FAQ {message:id=9360002} for how to use \ tags when posting formatted text.
(i.e displaying nulls when, if its possible, I want something like:
COLUMN HEADER: goalone goaltwo goalthree goal four goal five
ROW 1: Rooney Drogba Van Persie
ROW 2: Van Persie
e.g. It will only show goal scorers and not a huge list of Null none scorers.Sure, you can display NULLs any way you want.
that's the kind of thing your front end would be best at. In SQL*Plus, for example, you can saySET NULL ""
to have nothing display when a column is NULL.
If you had to do it in SQL, you could do something likeNVL (goalone, ' ')
to explicitly map NULL to a space.
On reflection there may even be better approaches to storing goal scorers but I'm against time now and i'm hoping there'll be a query to do something like what I want. I've only been able to find queries through Google that look for Nulls and then disregard the whole row if it finds one, which is obviously not what I want!It's quite unclear what you you want.
Perhaps the reason you can't find anything close to what you want is that what you want is a terrible thing to attempt in a relational database. This is what the first reply said, too.
Is foalone the person who happened to score the first goal in a particular game, goaltwo the person who scored the second goal (if there was a second goal), and so on? A much better way to model that would beCREATE TABLE goals
( game_id NUMBER (8)
, goal_num NUMBER (2) -- This assumes there will never be more than 99 goals in any one game
, player_id NUMBER (8)
You could have other columns, too, if you need them. Something to indicate the team might be handy, even if that can be derived from the player.
Any help is hugely appreciated! Thanks! :)Can you give a better idea of what kind of data your going to store, and what kind of questions this database will need to answer. Give some specific examples, like this:
"Two games were played. In the first game, Rooney scored a goa for team A, then Drogba and Van Persie scored goals for team B. In the second game, Van Persie scored the only goal for team B, and tem C didn't score at all. Some typical questions I'll want to answer are
(a) Who are the top scorers of all time? (With the sample data I just gave, I'd like to see output like this: ...)
(b) In what percentage of the games did player ... score?
(c) Given N specific players, what are the games when all N of them scored?
Here's something you may not realize about tables in relational databases, such as Oracle.
When tables are printed in books or papers, it's usually not important what the columns represent, and what the rows represent. For example, you may have a row for each player, and separate columns for name, age, team, and various statistics, but you might just as well have a column for each player (especially if you are comparing 2 or 3 players) and separate columns for name, age, team, and so on. *RELATION DATABASE TABLES DO NOT WORK LIKE THAT!* In a relational database, columns are relatively fixed things; for example, you must hard-code the number of columns into every query. Rows, on the other hand, are much more flexible. It's easy to write queries where the number of rows in the output will depend on what data happens to be in the table when the query is run. This is not intuitive, and may take some time to get used to, but you'll only cause trouble for yourself if you don't get the hang of it.
When I hear something like "show goal scorers and not a huge list of Null none scorers" it seems very obvious that there should be separate *rows* for the goal scorers. Again, I don't really knwo wht kind of data you want to keep, or how you plan to use that data, but if you're storing it in a relational database, that much seems obvious, -
How to add multiple columns using select statement
Hi friends
i have two TABLES
one table Contain only unique Agent code(23,45,56,88)
second table contain same Agent Code,orderdate & sum(amount)
now i want to add columns in table 1 according to date and update the amount in that column
for example if i select start date 1st july 2014 and end date is 15 july 2014
then i want result
select agentcode,amount as 01july2014,amount as 02nd july2014 up to 15th july
Please HELP.....>> I have two TABLES <<
Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. You failed on this too! Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. Ignorance is fine, but why do you have bad manners? The rules are posted at the front of the forum!
>> one [nameless, unknown] table Contain only unique Agent code(23, 45, 56, 88) <<
You do not know the difference between a code and an identifier!
CREATE TABLE Agents
(agent_id INTEGER NOT NULL PRIMARY KEY);
>> second table contain same Agent Code, order_date & SUM(order_amount) <<
Wrong again! The SUM() is an aggregate function and cannot be in a column. Tables have keys
CREATE TABLE Orders
(agent_id INTEGER NOT NULL
REFERENCES Agents(agent_id),
order_date DATE NOT NULL,
order_amt DECIMAL (8,2) NOT NULL,
PRIMARY KEY (agent_id, order_date));
>> now I want to add columns in table 1 according to date and update the amount in that column <<
NO! The running total is a computed column. We do not store them.
>> for example if I select start date 1st July 2014 [sic: 2014-07 -01] and end date is 15 July 2014 [sic: 2014-07-15] <<
If you have ever read a book on SQL, you would know the correct display format for dates! It is the only one in the ANSI/ISO Standards.
SELECT agent_id, order_date,
SUM(order_amt)
OVER (PARTITION BY agent_id
ORDER BY order_date
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
AS order_amt_runtot
FROM Orders
WHERE order_date BETWEEN '2014-07-01' AND '2014-07-15';
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Need to Pad char columns in select statements using JDBC
When issuing:
select * from tab1 where col1='ABC'
return o raws, if col1 is of type char(4).
Need to pad with spaces for RTRIM().
There is dicussion on Metalink. Is this fixed? An idea. ThanksYou probably mean:
PreparedStatement ps = conn.prepareStatement("select * from tab1 where col1=?")
ps.setString(1,"ABC");
ps.executeQuery();
Replace getString() with:
((oracle.jdbc.driver.OraclePreparedStatement)ps).setFixedCHAR(1,"ABC");
This should make the SELECT work.
null -
Compare columns SQL select statement (easy question)
Hi,
I need to write a query which compares every account's products to see if they match up with a corresponding service. Here is an example of my dataset.
Account_no products service
0001 prod1, prod2,prod3 serv1, serv2,serv3
0002 prod1,prod2,prod4 serv1,serv2,serv3,serv4
0003 prod1,prod2 serv1,serv2
I would like to pick up either a service or a product that does not have a matching pair, so in this example it would pick up account_no 0002 and shoe me the products, services so I can see which one doesn't have a match.
Thanks in advance for any help.
Joeselect * from table_name
where to_number(replace(replace(replace(products,'prod',''),',',''),' ','')) <>
to_number(replace(replace(replace(services,'prod',''),',',''),' ','')); -
Getting error while executing this select statement
Hi All,
I am new to this community.
I am getting error whie compiling the below code. Its telling 'Text' is invalid identifier. Also i want to know how can we obtain 'parseable' version of the below query?
my basic intention is to create a trigger header through a select statement and show it the complete text as a single column..
select text from
(select 'CREATE OR REPLACE TRIGGER '||SUBSTR(column_name,2,4)||'aud
AFTER INSERT
OR UPDATE
OF '||column_name||',
OR DELETE ON '||table_name||'
FOR EACH ROW'
FROM(SELECT lower(REPLACE(column_name,'O_','')) column_name , /*changing O to O_*/
lower(replace(t.table_name,'_A_','_')) table_name,
lower(t.table_name) table_name1,
c.column_id
FROM all_tab_columns c,
(SELECT object_name table_name
FROM all_objects
WHERE object_name LIKE '%/_A/_%' ESCAPE '/') t
WHERE c.table_name(+) = t.table_name
AND SUBSTR(column_name(+),1,2) = 'O_'))thanks prathamesh. it solved the problem. i have one more question.
as of now it creates single create trigger statement for each column on a table.
example:
CREATE OR REPLACE TRIGGER ust_aud
AFTER INSERT
OR UPDATE
OF cust_id,
OR DELETE ON characteristic_t
FOR EACH ROW
however, i want to create trigger for all columns in a single statement. can you please help me how to do it?
basically want to 'CREATE TRIGGER' for all columns in a table. i am finding difficult how to change my query to suit this!!
i am pasting my original query again for your reference. pls advise...
example:
CREATE OR REPLACE TRIGGER ust_aud
AFTER INSERT
OR UPDATE
OF cust_id,
fixed_item_val,
copy_item_val,
rgn_id,
txn_id,
OR DELETE ON characteristic_t
FOR EACH ROW
ORIGINAL QUERY
select text from
(select 'CREATE OR REPLACE TRIGGER '||SUBSTR(column_name,2,4)||'aud
AFTER INSERT
OR UPDATE
OF '||column_name||',
OR DELETE ON '||table_name||'
FOR EACH ROW' text
FROM(SELECT lower(REPLACE(column_name,'O_','')) column_name , /*changing O to O_*/
lower(replace(t.table_name,'_A_','_')) table_name,
lower(t.table_name) table_name1,
c.column_id
FROM all_tab_columns c,
(SELECT object_name table_name
FROM all_objects
WHERE object_name LIKE '%/_A/_%' ESCAPE '/') t
WHERE c.table_name(+) = t.table_name
AND SUBSTR(column_name(+),1,2) = 'O_'))
Maybe you are looking for
-
How to use value in a drop-down list box as "With these Values" parameter?
Hello, new user. I have a drop-down list box on Page 1, upon which the user can choose a study number. The List Box is named "P1_STUDY_NBR". Then I have a list, one entry of which goes to my master-detail form, which is Page 6. I would like it to go
-
Invalid seesion :- Worklist context is null
I'm creating the worklistapp from scratch. I have the TaskDetails.java servlet which redirects to taskdetails.jsp page. This page displays only the header and the payload form. The payload display page is a custom page and displays the payload correc
-
Capture/apply stopped by setting maximum_scn property, how back it infinite
For Maintenance reason, if we stopped the capture and apply process by setting maximum_scn property. How can we set it back to infinite when re-start the capture/apply process? Thanks john
-
How to exchanging data between SAP and P3?
could use BAPI directly between SAP and P3? And if we use XI as middleware, which protocols or methods should we use? any answer should be appreciated.
-
CC Installer quits halfway through
MBP Retina 15" (10.10.2, 2.6i7, 16GB/500GB): I have downloaded the installer 4 times now. I launch the installer and it begins to churn. Progress bar gets about halfway and the installer just quits. I have restarted, run Disk Utility to repair both p