Multiple Columns using a single CASE
Hi,
I have a SQL statement:
SELECT
CASE WHEN
c.code=b.code
AND c.from_id=b.to_id
THEN
COLA
ELSE
COLB
END "Exampl1"
CASE WHEN
c.code=b.code
AND c.from_id=b.to_id
THEN
DATEA
ELSE
DATEB
END "Exampl2"
FROM
table_a a,table_b b,
SELECT *
FROM
table_c
WHERE TYPE='REC') c
WHERE
a.code=b.code
I want to use the CASE statement one time not twice to fetch the required for Example1 and Example 2
Can it be possibleb?
Kindly any help will be benefitial to me
>
I want to use the CASE statement one time not twice to fetch the required for Example1 and Example 2
Can it be possibleb?
>
No - A CASE result is a singel statement and in a SELECT must be a single value.
So 'COLA' is ok but 'COLA, DATEA' will not work.
Just use the CASE once for each column like you are doing.
Similar Messages
-
Merge statement - update multiple columns from a single sub-select
Is it possible to write in 10gR2, a MERGE statement, with UPDATE for multiple columns from a single sub_select?
like this:
MERGE INTO tableA
using ( select * from temp) tmp
on( tableA. col1 = tmp.col1)
when matched then
update set ( tableA.col5,
tableA.col6,
tableA.col7) = ( select sum(col2), sum(col3), sum(col5)
from tableX
where tableX.col1 = tableA.col1...)Hi,
The USING clause is not a sub-query, so it can't reference columns from tables that are not in it.
Include tableA in the USING clause if you really need to refer to it there. (It's not obvious that you do.)
As always, it helps if you post:
(1) The version of Oracle (and any other relevant software) you're using
(2) A little sample data (just enough to show what the problem is) from all the relevant tables
(3) The results you want from that data (In the case of a DML statement, such as MERGE, this will be the state of the tables when everything is finished.)
(4) Your best attempt so far (formatted)
(5) The full error message (if any), including line number
Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
If you can present your problem using commonly available tables (for example, tables in scott schema, or views in the data dictionary), then you can omit (2).
Formatted tabular output is okay for (3). -
How to calculate the individual sums of multiple columns in a single query
Hello,
Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
Will appreciate any help or suggestion.
Thanksuser13667036 wrote:
Hello,
Using Oracle 11gR2 on windows 7 client. I have a question on calculating sum() on multiple columns on different columns and store the results in a view. Unfortunately I could not post the problem here as it keeps on giving error "Sorry, this content is not allowed", without telling where or what it is! So I had to post it in the stack-overflow forum, here is the link: http://stackoverflow.com/questions/16529721/how-to-calculate-the-individual-sums-of-multiple-columns-in-a-single-query-ora
Will appreciate any help or suggestion.
ThanksLooks like you want a simple group by.
select
yr
, mnth
, region
, sum(handled_package)
, sum(expected_missing_package)
, sum(actual_missing_package)
from test
group by
yr, mnth, region
order by
yr, mnth, region;I wouldn't recommend storing your data for year / month in 2 columns like that unless you have a really good reason. I would store it as a date column and add a check constraint to ensure that the date is always the first of the month, then format it out as you wish to the client.
CREATE TABLE test
year_month date,
Region VARCHAR2(50),
CITY VARCHAR2(50),
Handled_Package NUMBER,
Expected_Missing_Package NUMBER,
Actual_Missing_Package NUMBER
alter table test add constraint firs_of_month check (year_month = trunc(year_month, 'mm'));
ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
2 Values (to_date('2012-nov-12', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
ERROR at line 1:
ORA-02290: check constraint (TUBBY.FIRS_OF_MONTH) violated
Elapsed: 00:00:00.03
ME_XE?Insert into TEST (year_month, REGION, CITY, HANDLED_PACKAGE, EXPECTED_MISSING_PACKAGE, ACTUAL_MISSING_PACKAGE)
2 Values (to_date('2012-nov-01', 'yyyy-mon-dd'), 'Western', 'San Fransisco', 200, 10, 5);
1 row created.
Elapsed: 00:00:00.01
ME_XE?select
2 to_char(year_month, 'fmYYYY') as year
3 , to_char(year_month, 'fmMonth') as month
4 , Region
5 , CITY
6 , Handled_Package
7 , Expected_Missing_Package
8 , Actual_Missing_Package
9 from test;
YEAR MONTH REGION CITY HANDLED_PACKAGE EXPECTED_MISSING_PACKAGE ACTUAL_MISSING_PACKAGE
2012 November Western San Fransisco 200 10 5
1 row selected.
Elapsed: 00:00:00.01
ME_XE?Then you have nice a nice and easy validation that ensures you data integrity.
Cheers, -
Displaying data from multiple columns into a single line graph
Post Author: hollowmatrix
CA Forum: WebIntelligence Reporting
Hey,I have an issue with the WEBI reporting.I have a data source that has multiple columns say ( month1, month2, month3, month4,.....month 12, month 13, ....month24) with the sales data for each month.Now say I call the month 1 to month 12 as "current year", and call month 13 - month 24 as "previous year".I want to put a prompt in the report which allows me to select between "current year" and "previous year".Based on the prompt value we get a graph of the sales vs month ....as in if we select "current year", then we get a graph of the sales Vs time( remember that the sales data for each month is in a different column.)and if we select "previous year" then we get a graph of the sales Vs time for previous year..( sales vs time for Month 13, month 14, month 15....month 24).I am not able to pull data from multiple columns into a single object that I can use to populate the graphs.Any help on the same will be appreciated .Hi,
<p>
please click
here (asktom) and look for the words "how about the other way round"
</p> -
How to retrieve multiple columns using "returning" in the Insert query.
hi,
wanted to know how to retrieve multiple columns using "returning" in the Insert Query.
For retrieving one column we write the query as follows:
Insert into TABLE values(1,2,3,4) returning COLUMN1 into PARAMETER
But can we retrive multiple columns in the same query?
am using oracle 10g and coding in .NETHi,
You can definetely get multiple values from a single query using the 'returning' clause.
Eg : insert into emp (empno, ename, job, deptno) values (7324,'ADAM','MARKETING',30) returning ename, deptno into var1, var2; PN : var1 & var2 to be declared as varchar2 & number respectively.
More insight into the 'RETURNING' clause in this link.
http://www.samoratech.com/PLSQL/swArtPLSQLReturn.htm
Regards,
Bhanu. -
Multiple search using a single box...
in a form i have got aroun 10 rows and 10 columns.....is it possible to search the forms for the required information(i.e 10 different columns) using a single search box
You can use colon in any database item on runtime in entery query mode and it will prompt you to enter values/conditions on execute query where you can check any database item value. It will add the conditions in the where clause of the block. May be it will help in what you are looking for.
-
Multiple OUs using a single common WIP?
Multiple OUs using a single common WIP?
We have a manufacturing facility that contains tools and personnel that belong to multiple operating units (OU). Of course, the manufacturing part should work as if it is one site. Since all equipment and personnel work on all jobs there is no distinction between the higher level operating units and legal entities and books at the low level manufacturing point of view. However, costing must be costed appropriately by OU and the GL books of the seperate legal entities must be kept correctly and seperately.
How can Oracle Applications manufacturing modules be setup to handle a common manufacturing area used by personnel and equipment that is owned and costed by seperate OUs? I am unable to locate an example or reference to this type of situation in any manufacturing manuals.
ThanksNot sure that you will be able to find your example. You explain an interesting problem that is very unique. I do not think that you will find a standard system set up to meet your need. The work around solutions, that come to mind quickly, would require a standard cost environment and involve changing the period close process for manufacturing.
-
Inserting multiple rows using a single Insert statement without using dual
Hi all,
i am trying to insert multiple rows using a single insert statement like the below one.
The below one works fine..
But is there any other change that can be done in the below one without using dual...
insert all
into ps_hd_samp (num1,num2) values (1,1)
into ps_hd_samp (num1,num2) values (2,2)
into ps_hd_samp (num1,num2) values (3,3)
select 1 from dual;NiranjanSe wrote:
Hi all,
i am trying to insert multiple rows using a single insert statement like the below one.
The below one works fine..
But is there any other change that can be done in the below one without using dual...
insert all
into ps_hd_samp (num1,num2) values (1,1)
into ps_hd_samp (num1,num2) values (2,2)
into ps_hd_samp (num1,num2) values (3,3)
select 1 from dual;
SQL> create table ps_hd_samp (num1 number,num2 number);
Table created.
SQL> insert all
2 into ps_hd_samp (num1,num2) values (1,1)
3 into ps_hd_samp (num1,num2) values (2,2)
4 into ps_hd_samp (num1,num2) values (3,3)
5 select count(*)
6 from ps_hd_samp;
3 rows created.
SQL> select * from ps_hd_samp;
NUM1 NUM2
1 1
2 2
3 3 -
Update multiple rows & columns using a single statement
I have the following table with tablename - emp
first_name last_name age
aaa bbb 31
56
78
ggg hhh 36
2nd & 3rd row contain null values (no data) in first_name & last_name column . I want to update those two rows with data using a single statement. How do I do it?
I was thinking may be something like the following:-
UPDATE emp
SET first_name= , last_name=
CASE
WHEN age = 56 THEN 'ccc', 'ddd'
WHEN age = 78 THEN 'eee', 'fff'
ELSE first_name, last_name
END
-----------------------------------------------Can you give an example of a nested decode statement.
test@ora>
test@ora>
test@ora> --
test@ora> drop table t;
Table dropped.
test@ora> create table t as
2 select rownum x, cast(null as varchar2(10)) y from all_objects
3 where rownum <= 10;
Table created.
test@ora>
test@ora> select x, y from t;
X Y
1
2
3
4
5
6
7
8
9
10
10 rows selected.
test@ora>
test@ora> -- You want to change the values of y to 'a' through 'j' for x = 1 through 10
test@ora> -- and y = 'X' otherwise
test@ora> --
test@ora> -- Let's say the limit on the number of components were 12
test@ora> -- Then your decode statement would've been:
test@ora> --
test@ora> update t
2 set y = decode(x,
3 1, 'a',
4 2, 'b',
5 3, 'c',
6 4, 'd',
7 5, 'e',
8 'f');
10 rows updated.
test@ora>
test@ora>
test@ora> select x, y from t;
X Y
1 a
2 b
3 c
4 d
5 e
6 f
7 f
8 f
9 f
10 f
10 rows selected.
test@ora>
test@ora> -- As you can see you are unable to:
test@ora> --
test@ora> -- change y to 'g' if x = 7
test@ora> -- change y to 'h' if x = 8
test@ora> -- change y to 'i' if x = 9
test@ora> -- change y to 'j' if x = 10
test@ora> -- change y to 'X' otherwise
test@ora> --
test@ora>
test@ora> -- What you would do then is -
test@ora> -- (i) Let the 11 components remain as they are and
test@ora> -- (ii) Introduce a nested decode function *AS THE 12TH COMPONENT*
test@ora> --
test@ora>
test@ora> rollback;
Rollback complete.
test@ora>
test@ora> --
test@ora> update t
2 set y = decode(x,
3 1, 'a',
4 2, 'b',
5 3, 'c',
6 4, 'd',
7 5, 'e',
8 decode(x,
9 6, 'f',
10 7, 'g',
11 8, 'h',
12 9, 'i',
13 10, 'j',
14 'X')
15 );
10 rows updated.
test@ora>
test@ora> select x, y from t;
X Y
1 a
2 b
3 c
4 d
5 e
6 f
7 g
8 h
9 i
10 j
10 rows selected.
test@ora>
test@ora>HTH
isotope
Extrapolate that to 255 components and you get 254 + 255 = 509 components. And so on...
Message was edited by:
isotope -
Getting Multiple Recordsets using A Single Connection using jdbc-odbc
I have a java application which uses sql 7.0 database server. I want to have multiple recordsets created using a single connection using jdbc-odbc bridge. Kindly let me know the procedure.
Well, you create a recordset, then you create another one, and so on. Are you actually having a problem or you just don't know where to start?
-
Split flat file column data into multiple columns using ssis
Hi All, I need one help in SSIS.
I have a source file with column1, I want to split the column1 data into
multiple columns when there is a semicolon(';') and there is no specific
length between each semicolon,let say..
Column1:
John;Sam;Greg;David
And at destination we have 4 columns let say D1,D2,D3,D4
I want to map
John -> D1
Sam->D2
Greg->D3
David->D4
Please I need it ASAP
Thanks in Advance,
RH
sqlImports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Imports System.IO
Public Class ScriptMain
Inherits UserComponent
Private textReader As StreamReader
Private exportedAddressFile As String
Public Overrides Sub AcquireConnections(ByVal Transaction As Object)
Dim connMgr As IDTSConnectionManager90 = _
Me.Connections.Connection
exportedAddressFile = _
CType(connMgr.AcquireConnection(Nothing), String)
End Sub
Public Overrides Sub PreExecute()
MyBase.PreExecute()
textReader = New StreamReader(exportedAddressFile)
End Sub
Public Overrides Sub CreateNewOutputRows()
Dim nextLine As String
Dim columns As String()
Dim cols As String()
Dim delimiters As Char()
delimiters = ",".ToCharArray
nextLine = textReader.ReadLine
Do While nextLine IsNot Nothing
columns = nextLine.Split(delimiters)
With Output0Buffer
cols = columns(1).Split(";".ToCharArray)
.AddRow()
.ID = Convert.ToInt32(columns(0))
If cols.GetUpperBound(0) >= 0 Then
.Col1 = cols(0)
End If
If cols.GetUpperBound(0) >= 1 Then
.Col2 = cols(1)
End If
If cols.GetUpperBound(0) >= 2 Then
.Col3 = cols(2)
End If
If cols.GetUpperBound(0) >= 3 Then
.Col4 = cols(3)
End If
End With
nextLine = textReader.ReadLine
Loop
End Sub
Public Overrides Sub PostExecute()
MyBase.PostExecute()
textReader.Close()
End Sub
End Class
Put this code in ur script component. Before that add 5 columns to the script component output and name them as ID, col1, co2..,col4. ID is of data type int. Create a flat file destination and name it as connection and point it to the flat file as the source.
Im not sure whats the delimiter in ur flat file between the 2 columns. I have use a comma change it accordingly.
This is the output I get:
ID Col1
Col2 Col3
Col4
1 john
Greg David
Sam
2 tom
tony NULL
NULL
3 harry
NULL NULL
NULL -
Connection to multiple databases using a single EJB
How can I connect to multiple Databases (using @PersistenceContext) using an EJB?
Did I need to connect various Entity Managers corresponding to the each database and simply send my Queries?
I am using Glassfish Application Server
Netbeans IDE
Java Derby Database
Oracle Database
Java Persistence API
Thanks in AdvanceYes, you need a persistence context and thus entity manager per database. Depending on what you want to achieve you may also need to go to the next level in your skill set and learn all about distributed transactions.
-
Checking multiple columns using "IN"
I have a query
select 1 from tableA
where
cond1 = val1 and
exists
( col1, col2, col3, col4 ) IN
( select
cola, colb, colc, cold
from
table B
where
cond1 = val1
Will this condition Checking for multiple columns in the IN work ?
I actually mispelled a column name ( say colb ) in the sub query but it did not give a error, but executed fine by matching part of the columns alone?The execution plans look strangely similar.
SQL> CREATE TABLE t1 (c1 INT NOT NULL, c2 INT NOT NULL, c3 INT NOT NULL);
Table created.
SQL> INSERT INTO t1 (c1,c2,c3)
2 SELECT dbms_random.value(0,9)
3 , dbms_random.value(0,99)
4 , dbms_random.value(0,999)
5 FROM dual CONNECT BY LEVEL <= 10000;
10000 rows created.
SQL> CREATE TABLE t2 AS SELECT * FROM t1 SAMPLE BLOCK(10);
Table created.
SQL> BEGIN
2 DBMS_STATS.GATHER_TABLE_STATS(user,'T1');
3 DBMS_STATS.GATHER_TABLE_STATS(user,'T2');
4 END;
5 /
PL/SQL procedure successfully completed.
SQL> SELECT * FROM t1 WHERE (c1,c2,c3) IN
2 ( SELECT c1,c2,c3 FROM t2 )
3
SQL> @xplan
Plan hash value: 1275841967
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 18 | 12 (9)| 00:00:01 |
|* 1 | HASH JOIN RIGHT SEMI| | 1 | 18 | 12 (9)| 00:00:01 |
| 2 | TABLE ACCESS FULL | T2 | 209 | 1881 | 3 (0)| 00:00:01 |
| 3 | TABLE ACCESS FULL | T1 | 10000 | 90000 | 8 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - access("C1"="C1" AND "C2"="C2" AND "C3"="C3")
SQL> SELECT * FROM t1 WHERE EXISTS
2 ( SELECT NULL FROM t2
3 WHERE c1 = t1.c1
4 AND c2 = t1.c2
5 AND c3 = t1.c3 )
6
SQL> @xplan
Plan hash value: 1275841967
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 1 | 18 | 12 (9)| 00:00:01 |
|* 1 | HASH JOIN RIGHT SEMI| | 1 | 18 | 12 (9)| 00:00:01 |
| 2 | TABLE ACCESS FULL | T2 | 209 | 1881 | 3 (0)| 00:00:01 |
| 3 | TABLE ACCESS FULL | T1 | 10000 | 90000 | 8 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - access("C1"="T1"."C1" AND "C2"="T1"."C2" AND "C3"="T1"."C3")
SQL> -
Split single column into multiple column using sql /plsql
create table test (name varchar2(255);
insert into test values('DH RED 20 12/10 10 2 ');
insert into test values('PM STUD 20 15/10 20 29.55' );
insert into test values('LS MENTHOl FILTER ASC 18/70 60 240.66');
insert into test values('WINSTON WHITE CLASSIC 13 18/70 60 240.66');
My Output should be like as below in other table :
create table test_result (brand varchar2(255),packet varchar2(50),amount varchar2(25),total varchar2(25));
BRAND PACKET AMOUNT TOTAL
DH RED 20 12/10 10 2
PM STUD 20 15/10 20 29.55
LS MENTHOl FILTER ASC 18/70 60 240.66
WINSTON WHITE CLASSIC 13 18/70 60 240.66can you please help me to solve this issue
thanks in advance
Edited by: A on Apr 21, 2012 11:33 PM
Edited by: A on Apr 21, 2012 11:34 PM
Edited by: A on Apr 21, 2012 11:34 PMh4. # Database should be 10g. If version is below 10g query need to be modified as per string format.
h4. # Split string into two parts by '/'. First part contain brand + packet(1), Second part contain packet(2) + amount + total
h4. # Your brand name can be of any length.
String Format* : <Brand Name><space><packet(1)>/<packet(2)><space><amount><space><total>
SELECT name,
REGEXP_SUBSTR(first_part,'.+[[:space:]]',1,1) brand,
REGEXP_SUBSTR(first_part,'[^[:space:]]+/',1,1) || REGEXP_SUBSTR(second_part,'[^[:space:]]+[[:space:]]',1,1) packet,
REGEXP_SUBSTR(second_part,'[^[:space:]]+[[:space:]]',1,2) amount,
REGEXP_SUBSTR(second_part,'[^[:space:]]+$',1) total
FROM
(SELECT trim(name) name,
trim(substr(name,1, instr(name,'/'))) first_part,
trim(substr(name,instr(name,'/')+1)) second_part
FROM test )
{code} -
How to validate multiple controls using a single Validator?
I am trying to do an HourValidator because Flex doesn't have
this, so i am extending from the Validator class. I read in the
Creating and extending Flex components document the
following:
"A validator can validate more than one field at a time. For
example, you could create a custom
validator called NameValidator to validate three input
controls that represent a person’s first,
middle, and last names.
To create a validator that examines multiple fields, you can
either define properties on the
validator that let you specify the multiple input fields, as
does the Flex DateValidator class
class, or you can require that the single item passed to the
validator includes all of the fields to
be validated."
So according to the document i need to define properties so i
defined 4 properties:
startHourSource: the input control containing the starting
hour
startHourProperty: the control's property (in this case the
text property)
endHourSource: the input control containing the end hour
endHourProperty: the control's property (in this case the
text property)
The thing is that when i call the doValidation of the
superclass (to validate the required property) it does return a
validation error but it doesn't mark the input control with the red
frame that indicates there's a validation error. I assume that is
because the
source and
property properties of the validator are null but that's ok
because i am not using them, instead i am using the 4 properites
mentioned above.
So what do i need to do or override so the red frame appears
in the input controls??Yeah i already know that, but when you use the doValidation
method, which does the requiredField validation, by default marks
the input control with the red frame, so that's why i am trying to
do, doing it so it will do it by default.
For example, try this:
<mx:TextInput id="test"/>
<mx:Validator id="validateTest" source="{test}"
property="text" required="true" requiredFieldError="The field is
empty"/>
If you do
validateTest.validate( ) and the textinput is empty, it will
mark it with the red frame by default, that's the kind of behave i
want for my HourValidator, but if it is not possible then the
solution you suggested would be the only one to do this.
Maybe you are looking for
-
IPod touch library to new MacBook Pro
Previous computer was stolen so I do not have access to it. My iPod touch has over 1,000 songs, only some of which were purchased on iTunes. Does anyone know how I can get my ENTIRE iPod touch library into my new MacBook Pro iTunes library? Thanks fo
-
Flashing folder icon with question mark in the middle of the folder
LLashing folder icon with a question mark in middle of folder on startup
-
My internet used to sometimes lag a lot randomly so I decided to get the new modem that was also a router. All of my friends had it and it worked perfectly for everything. When I got it I tried to skype my friend and play some Team Fortress 2 with hi
-
Unable to Start/Stop Directory server from console
We have two Directory Server 5.2 installations with both running as masters with replication between them. One of them was installed with the admin server and the other without. On the one that was installed without the admin server we added it after
-
How do I upgrade iPad with IOS5.1.1 to IOS 6 when settings says software is up to date?