Using order by in Union ALL
hi Following is my query and am unable to accomplish my order by statement in Union All . please help me in this.
<code>
SELECT b.audit_trail_id,
TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
(u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
b.col_name "Field",
b.new_value "New Value",b.previous_value "Old Value",
a.lot_id,
b.comment_text "Comments"
FROM clem_audit_trail b,lot a, users u
WHERE a.lot_id = b.lot_id(+)
AND u.user_id(+) = b.last_update_user_id
AND a.lot_id in (select lot_id from request_lot where request_id = 51914)
AND col_name IN
('Interim Release Date',
'Final Disposition Date',
'On Time Disposition',
'Intended Use',
'REJECTS_YN',
'# of QARs',
'# of Quality Events',
'# of LIRs',
'# of Change Controls',
'# of Batch Records',
'# of GMP Batch Records',
'EXPLANATION',
'QA Notes',
'GDMS_LINK')
AND UPPER (table_name) IN('LOT') order by b.last_update_date
UNION ALL
SELECT b.audit_trail_id,
TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
(u.last_name || ', ' || u.first_name || ' ' || u.mi) "By",
b.col_name "Field",
b.new_value "New Value",b.previous_value "Old Value",
r.request_id,
b.comment_text "Comments"
FROM clem b,request r, users u
WHERE r.request_id = b.request_id(+)
AND u.user_id(+) = b.last_update_user_id
AND r.request_id = 51914
AND UPPER (table_name) IN ('REQUEST') AND
b.col_name IN ('Partial Release',
'All QP Docs in GDMS',
'Number of Batch Records',
'Request',
'QP Issues',
'Snag Comments',
'Responsible Group',
'Reason Late',
'Study Impact',
'Other Details',
'Request Status',
'QP Link to GDMS'
) order by b.last_update_date
</code>
If i execute individually it works fine, if i use union all it throughs error for me.
Any suggestion...
Hi,
In a set operation (such as UNION) table aliases (such as b.) only have meaning within the branch in which they are defined. The ORDER BY clause is not part of any 1 branch, so a table alias can't be used there.
In most cases, you can use a column name (or alias) from the first branch, like this:
SELECT b.audit_trail_id,
TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
order by "Revision Date"
;and you can always order by column number, like this:
SELECT b.audit_trail_id,
TO_CHAR (b.last_update_date, 'DD-Mon-YYYY') "Revision Date",
order by 2
;In this case, however, there's an extra problem. You're transforming the DATE to a string in the SELECT clause. The string is all that's available in the ORDER BY clause, and the string '19-NOV-2012' comes after the string '01-JAN-2015', because the character '1' comes after '0'. Perhaps the simplest solution is to have your front end, and not the query, format the dates. In SQL*Plus, you can do this:
ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY';
SELECT b.audit_trail_id,
b.last_update_date AS "Revision Date",
order by 2
I hope this answers your question.
If not, 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.
Always say what version of Oracle you're using (e.g. 11.2.0.2.0).
See the forum FAQ {message:id=9360002}
Similar Messages
-
Using ORDER BY in UNION clause in cursor
Hi Everybody,
I have one situation and i need your help guys. I have to use ORDER BY in UNION of two queries and return value in cursor.
OPEN cursor FOR
SELECT ID, DESC,SID, ITID, SID_DESC
FROM (SELECT A.ID,
A.DESC,
B.SID,
NULL AS ITID,
B.SID_DESC
FROM TABLEA A, TABLEB B
WHERE A.ID = B.ID
order by A.SORTORDER asc,B.SORTORDER)
UNION
SELECT ID, DESC, ,SID,ITID, ITID_DESCRIPTION,
FROM (SELECT A.ID,
A.DESC,
NULL AS SID,
C.ITID,
C.ITID_DESC,
FROM TABLEA A,
TABLEC C
WHERE A.ID = C.ID
order by A.SORTORDER asc,C.SORTORDER)
I SORT ORDER is column in all three tables. TABLEA has unique number for each record as sort order. TABLEB has sortorder as 1 for each id. If id is two times then its 1 and 2 for each id. TABLEC has sort order as TABLEB, 1 for each id and if id is two times then it is 1 and 2 and id id is three times, it is 1, 2, 3.
I am not getting correct sorting as i cant use order by like this in UNION. Please let me know how i can handle this.
Thank you in advance to everybody.
I will really appreciate your comments and responses.Hi,
You can use ORDER BY in a sub-query, but there's usually no point in doing so, because the super-query won't necessarily preserve that order. You need to make the columns that you want to ORDER BY available to the main query, so that they can be used there.
Try this:
SELECT ID, DESC,SID, ITID, SID_DESC
FROM (
SELECT A1.ID,
A1.DESC,
B.SID,
NULL AS ITID,
B.SID_DESC,
A1.SORTORDER AS sortorder_1
B.SORTORDER AS sortorder_2
FROM TABLEA A1,
TABLEB B
WHERE A1.ID = B.ID
UNION
SELECT A2.ID,
A2.DESC,
NULL AS SID,
C.ITID,
C.ITID_DESC,
A2.SORTORDER AS sortorder_1
B.SORTORDER AS sortorder_2
FROM TABLEA A2,
TABLEC C
WHERE A2.ID = C.ID
order by SORTORDER_1 ASC -- ASC is the default, but it doesn't hurt to say it
SORTORDER_2This assumes that tableb.sortorder and tablec.sortorder have the same, or at least similar, data types. If not, explicitly convert sortorder_1 in one branch of the UNION to the type of sortorder_2 in the other branch.
Using the same alias to mean different things in the same query is just asking for trouble. I changed the table alias a (which was used in different places to mean two different things) to A1 and A2, each of which means only one thing.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
Explain, using specific examples, how you get those results from that data.
Always say which version of Oracle you're using. -
Syntax Error - Using "Group By" with "Union All"
Dear SAP community, I am a newb in need of help.
Just spent the past 2 days searching for answers on how to build this query.
Basically, I just want to group the Item Names (U_ItemName) together and have their respective quantities (U_Cart) added together so the same items display as one total quantity, no duplicates.
I have tried so many combinations of GroupBy and Sum/Count....etc. Nothing is working.
The query:
SELECT T1.[U_ItemName] AS 'Item Name', T1.[U_Cart] AS 'Cartons Available', T0.[Country] AS 'Country', T1.[U_ShlfLife] AS 'Shelf Life' FROM [dbo].[OWHS] T0 inner join [dbo].[@SICAS_EXT_WHS] T1 on T0.WhsCode=T1.U_WhseCode WHERE T0.[Country] = (N'JP' ) and DateDiff(Month, GetDate(),T1.[U_ShlfLife]) <= 6 union all
SELECT T0.[U_ItemName], Sum(T0.[U_Cart]) as Cartons, T1.[Country], null FROM [dbo].[@SICAS_EXT_WHS] T0, OWHS T1 WHERE T1.[Country] = (N'JP' ) and DateDiff(Month, GetDate(),T0.[U_ShlfLife]) >= 6
GROUP BY T0.[U_ItemName], T0.[U_Cart], T1.[Country]
Can anybody advise how to get this working?
Thank you,
Justice Nerenberghi justice,
I checked your code and it seems correct. but I don't have same table in database so i can't check it correctly.
but I tried your problem with same situation and I am getting actual result.
Example :-
select itemcode,dscription,quantity from inv1
where docdate>'2011-02-18 00:00:00.000'
union all
select itemcode,dscription,Sum(quantity) from inv1
where docdate<'2011-02-18 00:00:00.000'
group by itemcode,dscription
Please do one thing rum both select queries separately whether running properly. Using above example you can check your code
Thanks
Annu -
Using order by with the UNION ALL operator
Hi,
I have 2 queries and i'm using UNION ALL to join both of them.
And i want to sort the final result based on a column.
When i try to do that, its not allowing me to use the ORDER BY clause.
Any suggestions??
Example
select * from xxx where job='Manager'
order by ename
union all
select * from yyy where job='Engineer'
order by ename
Thanks in advance
--KumarSQL> select * from test_emp where deptno = 10 order by ename
2 union all
3 select * from test_emp where deptno = 20 order by ename;
union all
ERROR at line 2:
ORA-00933: SQL command not properly ended
SQL> select * from test_emp where deptno = 10 --order by ename
2 union all
3 select * from test_emp where deptno = 20 order by ename;
select * from test_emp where deptno = 20 order by ename
ERROR at line 3:
ORA-00904: "ENAME": invalid identifier
SQL> select * from test_emp where deptno = 10 --order by ename
2 union all
3 select * from test_emp where deptno = 20 --order by ename;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-81 3141 1 10
7782 CLARK MANAGER 7839 09-JUN-81 2700 10
7839 KING PRESIDENT 17-NOV-81 5512 10
7934 MILLER CLERK 7782 23-JAN-82 1433 10
7369 SMITH CLERK 7902 10-OCT-06 882 123 20
7566 JONES MANAGER 7839 10-OCT-06 3279 123 20
7788 SCOTT ANALYST 7566 11-OCT-06 3307 123 20
7876 ADAMS CLERK 7788 10-OCT-06 1212 123 20
7902 FORD ANALYST 7566 10-OCT-06 3307 123 20
9 rows selected.
SQL> select * from
2 (select * from test_emp where deptno = 10 union all
3 select * from test_emp where deptno = 20)
4 order by ename;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7876 ADAMS CLERK 7788 10-OCT-06 1212 123 20
7698 BLAKE MANAGER 7839 01-MAY-81 3141 1 10
7782 CLARK MANAGER 7839 09-JUN-81 2700 10
7902 FORD ANALYST 7566 10-OCT-06 3307 123 20
7566 JONES MANAGER 7839 10-OCT-06 3279 123 20
7839 KING PRESIDENT 17-NOV-81 5512 10
7934 MILLER CLERK 7782 23-JAN-82 1433 10
7788 SCOTT ANALYST 7566 11-OCT-06 3307 123 20
7369 SMITH CLERK 7902 10-OCT-06 882 123 20
9 rows selected.
SQL> -
Is the order in which a UNION ALL query returns rows guaranteed?
Guys
I'm doing a kind of query where I want to return matching rows in a priority order and take the first one. THink of it as getting the most specific error message for a particular context.
SELECT * FROM (
SELECT msg FROM errormessages WHERE device = 'x'
UNION ALL
SELECT msg FROM errormessages WHERE client = 'y'
UNION ALL
SELECT msg FROM (SELECT msg from errormessages WHERE class LIKE 'generic_' ORDER BY class)
UNION ALL
SELECT 'missing error message' FROM dual
WHERE ROWNUM =1
If UNION ALL is guaranteed to return rows in this order, great. If not, would it be better to have:
SELECT * FROM ( SELECT * FROM(
SELECT 1 as ord, msg FROM errormessages WHERE device = 'x'
UNION ALL
SELECT 2, msg FROM errormessages WHERE client = 'y'
UNION ALL
SELECT 4+SUBSTR(class, 7, 1), msg FROM errormessages WHERE class LIKE 'generic_'
UNION ALL
SELECT 9999, 'missing error message' FROM dual
) ORDER BY ord )
WHERE ROWNUM =1Or, another option:
SELECT msg FROM(
SELECT
CASE
WHEN device = 'x' THEN 1
WHEN client = 'y' THEN 2
WHEN class LIKE 'generic_' THEN 4+SUBSTR(class, 7, 1)
END as ord, msg
FROM (
SELECT * FROM errormessages WHERE device = 'x' OR client = 'y' OR class LIKE 'generic_'
UNION ALL
SELECT 999, 'missing error' FROM dual
) ORDER BY ord
)WHERE ROWNUM =1As you can see there is a complication in the generic; devices may advertise that they accept 1,2,3 or 4 lines of info, so I want to use the advertised capabiltiy to pick the most relevant message from the generic set if no specifics exist for the device or the client
Which was would you go?
Cheers
Edited by: charred on Feb 11, 2009 4:56 AM - code tagscharred wrote:
So tell me guys, do I go for:
4 queries unioned together
or
1 query with 4 ORs in the where clause and a case when to determine priority?It will depend on your conditions, but if you look at your explain plans you should get an idea for which is the better one; typically I would expect this to be the OR method...
SQL> select * from emp where deptno = 20
2 union all
3 select * from emp where job = 'CLERK'
4 union all
5 select * from emp where sal > 2500;
Execution Plan
Plan hash value: 3153085224
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 14 | 546 | 8 (75)| 00:00:01 |
| 1 | UNION-ALL | | | | | |
| 2 | TABLE ACCESS BY INDEX ROWID| EMP | 5 | 195 | 2 (0)| 00:00:01 |
|* 3 | INDEX RANGE SCAN | DEPT_IDX | 5 | | 1 (0)| 00:00:01 |
|* 4 | TABLE ACCESS FULL | EMP | 4 | 156 | 3 (0)| 00:00:01 |
|* 5 | TABLE ACCESS FULL | EMP | 5 | 195 | 3 (0)| 00:00:01 |
Predicate Information (identified by operation id):
3 - access("DEPTNO"=20)
4 - filter("JOB"='CLERK')
5 - filter("SAL">2500)
Statistics
1 recursive calls
0 db block gets
18 consistent gets
1 physical reads
0 redo size
1328 bytes sent via SQL*Net to client
396 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
14 rows processed
SQL> select * from emp
2 where deptno = 20 or job = 'CLERK' or sal > 2500;
Execution Plan
Plan hash value: 3956160932
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
| 0 | SELECT STATEMENT | | 10 | 390 | 3 (0)| 00:00:01 |
|* 1 | TABLE ACCESS FULL| EMP | 10 | 390 | 3 (0)| 00:00:01 |
Predicate Information (identified by operation id):
1 - filter("DEPTNO"=20 OR "SAL">2500 OR "JOB"='CLERK')
Statistics
1 recursive calls
0 db block gets
8 consistent gets
0 physical reads
0 redo size
1146 bytes sent via SQL*Net to client
396 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
0 sorts (memory)
0 sorts (disk)
9 rows processed
SQL> -
Hi,
Is Order by in Union ALL query allowed? If not what is the solution while using Unoin ALL?
thxWhat isn't working? These are all OK:
SELECT dummy FROM dual
UNION ALL
SELECT dummy FROM dual
ORDER BY dummy;
SELECT dummy FROM dual
UNION ALL
SELECT dummy FROM dual
ORDER BY 1;
SELECT dummy AS c1 FROM dual
UNION ALL
SELECT dummy FROM dual
ORDER BY c1;The name used in the ORDER BY clause has to be one of the names in the first SELECT list, or a number. -
TSQL verify sort order / UNION ALL
CREATE PROCEDURE Test
AS
BEGIN
SELECT * FROM (
SELECT 1 AS a,'test1' as b, 'query1' as c
UNION ALL
SELECT 2 AS a,'test22' as b, 'query22' as c
UNION ALL
SELECT 2 AS a,'test2' as b, 'query2' as c
UNION ALL
SELECT 3 AS a,'test3' as b, 'query3' as c
UNION ALL
SELECT 4 AS a,'test4' as b, 'query4' as c
) As sample
FOR XML RAW
END
Can we guarantee that the stored procedure returns results in given order?
Normally it says when we insert these select query to temporary table we can't guarantee its inserting order. So we have to use order by clause. But most of time it gives same order. Can we enforce to give it some different order? Is this related with clustered
and non clustered indices.
In second case can we enforce inserting order by adding Identity column?
Explain more on behind logic as well. I'm checking whether I need to add ORDER BY in old Stored Procedures or not.Can we guarantee that the stored procedure returns results in given order?
No. The only way to get a guaranteed order is to use an ORDER BY clause.
Normally it says when we insert these select query to temporary table we can't guarantee its inserting order. So we have to use order by clause. But most of time it gives same order. Can we enforce to give it some different order? Is this related with
clustered and non clustered indices.
The only way to get a guaranteed order is to use an ORDER BY clause. Anything else is happenstance.
In second case can we enforce inserting order by adding Identity column? Explain more on behind logic as well. I'm checking whether I need to add ORDER BY in old Stored Procedures or not.
Again: the only way to get a guaranteed order is to use an ORDER BY clause.
Erland Sommarskog, SQL Server MVP, [email protected] -
Query using Union All and CTEs is slow
TypePatient
[ednum] int NOT NULL, PK
[BackgroundID] int NOT NULL, FK
[Patient_No] varchar(50) NULL, FK
[Last_Name] varchar(30) NULL,
[First_Name] varchar(30) NULL,
[ADateTime] datetime NULL,
Treat
[ID] int NOT NULL, PK
[Ednum] numeric(10, 0) NOT NULL, FK
[Doctor] char(50) NULL,
[Dr_ID] numeric(10, 0) NULL,
background
[ID] int NOT NULL, PK
[Patient_No] varchar(50) NULL, FK
[Last_Name] char(30) NULL,
[First_Name] char(30) NULL,
[DateofBirth] datetime NULL,
pdiagnose
[ID] int NOT NULL, PK
[Ednum] int NOT NULL, FK
[DSMNo] char(10) NULL,
[DSMNoIndex] char(5) NULL,
substance
[ID] int NOT NULL, PK
[Ednum] int NOT NULL, FK
[Substance] varchar(120) NULL,
DXCAT
[id] int NULL, PK
[dx_description] char(100) NULL,
[dx_code] char(10) NULL,
[dx_category_description] char(100) NULL,
[diagnosis_category_code] char(10) NULL)
Substance
ID
Ednum
Substance
1
100
Alcohol Dependence
4
200
Caffeine Dependence
5
210
Cigarettes
dxcat
id
dx_description
dx_code
dx_category_description
diagnosis_category_code
10
Tipsy
zzz
Alcohol
SA
20
Mellow
ppp
Mary Jane
SA
30
Spacey
fff
LSD
SA
50
Smoker
ggg
Nicotine
SA
pdiagnose
ID
Ednum
DSMNo
Diagnosis
1
100
zzz
Alcohol
2
100
ddd
Caffeine
3
210
ggg
Smoker
4
130
ppp
Mary Jane
TypePatient
ednum
Patient_No
Last_Name
First_Name
ADateTime
100
sssstttt
Wolly
Polly
12/4/2013
130
rrrrqqqq
Jolly
Molly
12/8/2013
200
bbbbcccc
Wop
Doo
12/12/2013
210
vvvvwww
Jazz
Razz
12/14/2013
Treat
ID
Ednum
Doctor
Dr_ID
2500
100
Welby, Marcus
1000
2550
200
Welby, Marcus
1000
3000
210
Welby, Marcus
1000
3050
130
Welby, Marcus
1000
background
ID
Patient_No
Last_Name
First_Name
DateofBirth
2
sssstttt
Wolly
Polly
8/6/1974
3
rrrrqqqq
Jolly
Molly
3/10/1987
5
bbbbcccc
Wop
Doo
8/12/1957
6
vvvvwww
Jazz
Razz
7/16/1995
Desired output:
Staff ID
Doctor
Patient_No
Client Name
Date of Service
Ednum
DX Code
DX Cat
DX Desc
Substance
1000
Welby, Marcus
bbbcccc
Wop, Doo
12/12/2013
200
Caffeine Dependence
1000
Welby, Marcus
rrrqqq
Jolly, Molly
12/8/2013
130
ppp
SA
Mary Jane
1000
Welby, Marcus
sssttt
Wolly, Polly
12/4/2013
100
zzz
SA
Alcohol
1000
Welby, Marcus
sssttt
Wolly, Polly
12/4/2013
100
ddd
SA
LSD
1000
Welby, Marcus
sssttt
Wolly, Polly
12/4/2013
100
Alcohol Dependence
1000
Welby, Marcus
vvvvwww
Jazz, Razz
12/14/2013
210
ggg
SA
Smoker
1000
Welby, Marcus
vvvvwww
Jazz, Razz
12/14/2013
210
Cigarettes
A patient is assigned an ednum. There are two different menus for staff to enter
diagnoses. Each menu stores the entries in a different table. The two tables are substance and pdiagnose. A patient’s diagnosis for a substance abuse can be entered in one table and not the other.
The number of entries for different substances for each patient can vary between the two tables. John Doe might be entered for alcohol and caffeine abuse in the pdiagnosis table and entered only for caffeine abuse in the substance table. They are only
linked by the ednum which has nothing to do with the diagnosis/substance. The substance entered in one table is not linked to the substance entered in the other. A query will not put an entry for alcohol from the pdiagnosis table on the same row as an alcohol
entry from the substance table except by chance. That is the reason for the way the query is written.
The query accepts parameters for a Dr ID and a start and end date. It takes about 7 to 15 seconds to run. Hard coding the dates cuts it down to about a second.
I might be able to select directly from the union all query instead of having it separate. But then I’m not sure about the order by clauses using aliases.
Is there a way to rewrite the query to speed it up?
I did not design the tables or come up with the process of entering diagnoses. It can’t be changed at this time.
Please let me know if you notice any inconsistencies between the DDLs, data, and output. I did a lot of editing.
Thanks for any suggestions.
with cte_dxcat (Dr_ID, Doctor, Patient_No,Last_Name,
First_Name, Adatetime,Ednum,
dx_code,diagnosis_category_code,dx_description,substance,
DateofBirth) as
(Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
TP.First_Name, TP.Adatetime as 'Date of Service',TP.Ednum,
DXCAT.dx_code,DXCAT.diagnosis_category_code,DXCAT.dx_description,
null as 'substance',BG.DateofBirth
From TypePatient TP
inner join treat t on TP.ednum = t.Ednum
inner join background BG on BG.Patient_No = TP.Patient_No
inner join pdiagnose PD on TP.Ednum = PD.Ednum
inner join Live_Knowledge.dbo.VA_DX_CAT_MAPPING DXCAT on DXCAT.dx_code = PD.DSMNo
Where (TP.Adatetime >= convert(varchar(10), :ST, 121)+ ' 00:00:00.000'
and TP.Adatetime <= convert(varchar(10), :SP, 121)+ ' 23:59:59.000')
and DXCAT.diagnosis_category_code = 'SA'
and t.Dr_ID =:DBLookupComboBox2
cte_substance (Dr_ID, Doctor, Patient_No,Last_Name,
First_Name,Adatetime, Ednum,
dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
(Select distinct t.Dr_ID, t.Doctor, TP.Patient_No,TP.Last_Name,
TP.First_Name, TP.Adatetime as 'Date of Service', TP.Ednum,
null as 'dx_code',null as 'diagnosis_category_code',null as 'dx_description',s.Substance, BG.DateofBirth
From TypePatient TP
inner join treat t on TP.ednum = t.Ednum
inner join background BG on BG.Patient_No = TP.Patient_No
inner join pdiagnose PD on TP.Ednum = PD.Ednum
inner join substance s on TP.Ednum = s.Ednum
Where (TP.Adatetime >= convert(varchar(10), '12/1/2013', 121)+ ' 00:00:00.000'
and TP.Adatetime <= convert(varchar(10), '12/31/2013', 121)+ ' 23:59:59.000')
and t.Dr_ID =:DBLookupComboBox2
cte_all (Dr_ID, Doctor, Patient_No,Last_Name,
First_Name,Adatetime, Ednum,
dx_code,diagnosis_category_code,dx_description,Substance,DateofBirth) as
(select cte_dxcat.Dr_ID as 'Staff ID', cte_dxcat.Doctor as 'Doctor',
cte_dxcat.Patient_No as 'Patient_No',
cte_dxcat.Last_Name as 'Last',cte_dxcat.First_Name as 'First',
cte_dxcat.Adatetime as 'Date of Service',cte_dxcat.Ednum as 'Ednum',
cte_dxcat.dx_code as 'DX Code',cte_dxcat.diagnosis_category_code as 'DX Category Code',
cte_dxcat.dx_description as 'DX Description',
cte_dxcat.substance as 'Substance',cte_dxcat.DateofBirth as 'DOB'
from cte_dxcat
union all
select cte_substance.Dr_ID as 'Staff ID', cte_substance.Doctor as 'Doctor',
cte_substance.Patient_No as 'Patient_No',
cte_substance.Last_Name as 'Last',cte_substance.First_Name as 'First',
cte_substance.Adatetime as 'Date of Service',cte_substance.Ednum as 'Ednum',
cte_substance.dx_code as 'DX Code',cte_substance.diagnosis_category_code as 'DX Category Code',
cte_substance.dx_description as 'DX Description',
cte_substance.substance as 'Substance',cte_substance.DateofBirth as 'DOB'
from cte_substance)
select cte_all.Dr_ID as 'Staff ID', cte_all.Doctor as 'Doctor',
cte_all.Patient_No as 'Patient_No',
(cte_all.Last_Name + ', '+ cte_all.First_Name) as 'Client Name',
cte_all.Adatetime as 'Date of Service',cte_all.Ednum as 'Ednum',
cte_all.dx_code as 'DX Code',cte_all.diagnosis_category_code as 'DX Category Code',
cte_all.dx_description as 'DX Description',
cte_all.substance as 'Substance',
CONVERT(char(10), cte_all.DateofBirth,101) as 'DOB'
from cte_all
order by cte_all.Patient_No,cte_all.AdatetimePlease post real DDL instead of your invented non-language, 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. Your rude, non-SQL narrative is so far away from standards I cannot even use you as a bad example in book.
Temporal data should use ISO-8601 formats (we have to re-type the dialect you used!). Code should be in Standard SQL as much as possible and not local dialecT.
This is minimal polite behavior on SQL forums. You posted a total mess! Do you really have patients without names?? You really use a zero to fifty characters for a patient_nbr??? Give me an example. That is insane!
Your disaster has more NULLs than entire major corporate systems. Since you cannot change it, can you quit? I am serious. I have been employed in IT since 1965, and can see a meltdown.
I looked at this and I am not even going to try to help you; it is not worth it. I am sorry for you; you are in an environment where you cannot learn to do any right.
But you are still responsible for the rudeness of not posting DDL.
--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 -
Order by decode statement with Union all
Hi
I use Database Version: Oracle 9.2.0.1.0
OCI version 9.2
I try to use order by decode while i have a select base on union and I get en error:
ORA-01785: ORDER BY item must be the number of a SELECT-list expression
Here is my code:
select catalog_type, catalog_id, item_id, item_name
from items_catalog
union all
select catalog_type, catalog_id, organisation_unit_id, organisation_unit_name
from units_catalog
order by decode(catalog_type, 1, item_id, organisation_unit_id)
If I use the decode on a select statement without union, it works.
What I have to do in order to make it work on union all select?
TnxHi,
Here's a slightly different way:
COLUMN sort_key NOPRINT
VARIABLE catalog_type_wanted VARCHAR2 (5)
EXEC :catalog_type_wanted := '4';
SELECT catalog_id, item_id, item_name
, CASE
WHEN :catalog_type_wanted = '1' THEN '1'
ELSE '2'
END || item_id AS sort_key
FROM items_catalog
UNION ALL
SELECT catalog_id, organisation_unit_id, organisation_unit_name
, CASE
WHEN :catalog_type_wanted = '1' THEN '2'
ELSE '1'
END || organisation_unit_name AS sort_key
FROM units_catalog
ORDER BY sort_key
;This way guarantees that (for example) 'SHOP50' comes before 'SHOP58', whether or not they are in the first half of the output or the second half.
Notice that this uses the SQL*Plus COLUMN ... NOPRINT command to hide the sort_key column.
If you're not using SQL*Plus, then whatever front end you are using may have a similar feature.
If not, then you can do the UNION in a sub-query, as Daniel did, but do the ORDER BY in the main query (only). -
Different results using View with union all in 11R1 compared to 10R2
Hello,
I have the following situation:
In Oracle 10R2 I defined a view which looks like this
create view test_view
as
select 'field1;field2;field3' field from dual
union all
select field
from (
select tfield1||';'||tfield2||';'||tfield3 field
from table1
order by tfield1,tfield2,tfield3
The idea is, my first line contains a header information an then the data in the required sorting order.
So, in 10R2, when I export the view with select field from test_view, I get the result as expected, which means, the header from the part with the dual was in the first line and after that, the data in the required sort order.
Now, in 11.1.0.7, it is completely different, because the row of the dual is somewhere in my result set. But if I send the sql instead of the view, I get the expected result as in 10R2.
I have no idea why this is the case now, because in 10R2 this was working permanently as expected. When I look at the execution plan, I see, that he starts parallelisation, which is ok, but the difference is, that in this parallelisation the select from dual is included and in 10R2 he first make the line from the dual and then the parallelisation with the data. It's not clear to me, that if I send the sql to the database I see the required result, but if i define the view as mentioned, and start a select field from view, I get now get the different sorting, because of the parallelisation, where the optimizer he changes his behavior comparing the both database versions. So my question ist, how can I change this behavior to get the same behavior as in release 10R2.
Best regards
RainerHello,
thank you for your sample, I see your idea for my sorting purpose.
I want to look at the following point:
I create the table, as you described. The table has the degree and instances 1. Now I deefine the following view:
create view view_test
as
select 'field1;field2;field3' field
from dual
union all
select tfield1 || ';' || tfield2 || ';' || tfield3 field
from (select * from table1 order by tfield1,tfield2).
This is the way I used it in 10 R2.
Now, the SQL select field from view_test delivers the expected result:
field1;field2;field3
a;b;c
d;e;f
So far so good. But now, I changed the degree of the table1 (alter table table1 parallel (degree 4 instances 1);).
The result looks like that:
a;b;c
field1;field2;field3
d;e;f
So, the parallelisation of my object seems to be the reason for the, in my eyes, "wrong" sort order. In 10R2 I used this degree and instance values for my table and defined a view and it was working fine. Now, after our migration, I had this "trouble". For me it seems, that the optimizer made some changes, or mabe this is a bug, who knows ?
I also tried, to change the nls_comp, and set the undocumented parameters as described in the Metalink note 7497640.8, but with no effect of my result set.
Best regards
Rainer -
Select extra row without using UNION ALL in pl/sql
Hi,
Can anyone tell me how to select extra row without using UNION or UNION ALL in pl/sql. Actually I want to have my o/p of query as partitioned by designation and ordered by salary and than one extra row which will contain the highest salary in a particular salary. My table has first_name,emp_id,designation and salary column. And I wnt the o/p as.
Mohinish,12212,SI,46000
Ram,11212,SSI,47000
Shyam,12133,SI,48000
Rick,9898,SI,46000
Rocky,12312,SSI,56000
Sariq,23948,SI,43000
Suman,12789,HR,49000
Sampy,12780,SI,46000
Parna,11111,HR,50000
Now the o/p should be.
Mohinish,12212,SI,46000
Rick,9898,SI,46000
Sariq,23948,SI,43000
Shyam,12133,SI,48000
Shyam,12133,SI,48000
Ram,11212,SSI,47000
Rocky,12312,SSI,56000
Rocky,12312,SSI,56000
Suman,12789,HR,49000
Parna,11111,HR,50000
Parna,11111,HR,50000
Thanks in AdvanceYou don't have to do a UNION or UNION ALL in PL/SQL but you would need to in SQL to get the desired output:
with data_recs
as (select 'Mohinish' first_name,12212 emp_id,'SI' designation,46000 salary from dual union
select 'Ram',11212,'SSI',47000 from dual union
select 'Shyam',12133,'SI',48000 from dual union
select 'Rick',9898,'SI',46000 from dual union
select 'Rocky',12312,'SSI',56000 from dual union
select 'Sariq',23948,'SI',43000 from dual union
select 'Suman',12789,'HR',49000 from dual union
select 'Sampy',12780,'SI',46000 from dual union
select 'Parna',11111,'HR',50000 from dual)
select first_name, emp_id, designation, salary from data_recs union all
select s.first_name, s.emp_id, s.designation, s.salary
from (select first_name,
emp_id,
designation,
salary,
row_number() over (partition by designation order by salary desc) high_salary
from data_recs
order by designation, salary) s
where s.high_salary = 1
order by designation, salary;
FIRST_NAME EMP_ID DESIGNATION SALARY
Suman 12789 HR 49000
Parna 11111 HR 50000
Parna 11111 HR 50000
Sariq 23948 SI 43000
Rick 9898 SI 46000
Mohinish 12212 SI 46000
Sampy 12780 SI 46000
Shyam 12133 SI 48000
Shyam 12133 SI 48000
Ram 11212 SSI 47000
Rocky 12312 SSI 56000
Rocky 12312 SSI 56000 -
Hello
i have 2 schemas S1 and S2 containing complex relational tables. The tables in each schema are related to each other via foreign key relationships. i made views for feature tables in both the schemas , querying column values from their related tables.
the data structure in both the schemas are exactly the same. Dut to management reasons we have to split them in 2 schemas. S1 contain data for region A and S2 contains data from region B. Now the client wants to see a combined data from region A & B.
we are planning to create another schema S3 and make views combining views from S1 and S2 in both schemas (V1 in S1 + V1 in S2) using UNION ALL.
Does UNION ALL will make use of the indexes we already built for parent tables in S1 and S2? Will there be a performance degradation using this approach? What can be the best approach? Our client needs to see real time data....
regards
samSince union does an extra sort it has a performance difference compared to union all.
SQL> select user from dual union select user from dual ;
USER
HR
SQL> select user from dual union all select user from dual ;
USER
HR
HRİf there is up to date and appropriate object statistics Oracle's Cost Based Optimizer will choose best access path, join method and join order depending on your query. Only exceptions are hints, outlines and sql profiles since they stabilize the execution plan.
For further commenting please post your oracle version, query's test results and its statistics taken from sql*plus timing and autotrace options - http://www.bhatipoglu.com/entry/17/oracle-performance-analysis-tracing-and-performance-evaluation -
Select query-using Union All display duplicate records.
Hello All Gurus-
I am using Oracle 9.i
When i use the following query to fetch the records based on BUILDNUMBERNAME and ASSIGNED_BUILD then i am getting duplicate records -
select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
Union All
select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
How can i use the order by on T1.ID ? When i use the Order by T1.ID then it throws some error.
Kindly help me in this :(
Thanks in advance.Sorry for not providing all of the details -
I am using Toad tool to run the query.
1-When i use the following query -
Select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6' order by T1.ID
Union All
select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6' order by T1.ID
ORA-00933: SQL command not properly ended.
2-If i am not using the T1.ID and run the following query
Select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1. ASSIGNED_BUILD like '1.4.5.6'
Union All
select T1.ID FROM Defect T1,statedef T2,repoproject T3
WHERE T1.STATE=T2.ID AND T1.repoproject = T3.dbid AND T3.name Like 'ABC' AND T1.BUILDNUMBERNAME like '1.4.5.6'
Then it is running fine but it is displaying the duplicate values like -
00089646
00087780
00089148
00090118
00090410
00088503
00080985
00084526
00087108
00087109
00087117
00088778
00086714
00079518
00087780
00089148
00090392
00090393
00090395
00090398
00090401
00090402
00090403
00090406
00090408
00088503
00080985
00084526
00087108
00087109
00087117
00088778
00086714
00079518 -
Inventory on Hand Report - Using Union ALL - need two fields to be part of the group
Hi all,
I have created an Inventory "on Hand" Report that takes the Current Inventory from the Item Entry table and the Sales from Unposted Sales Line table and Transfers in and out from the Unposted Transfer Line table. I have joined the tables
using the UNION ALL function.
My problem is that the Transfer table has two locations whereas the other tables only have one. I am grouping on Location code from the Item Entry table which is equivalent to BOTH Transfer from location and the Transfer to.
As an example, there are 15lbs of inventory for Product A in Location #1 with a transfer out of 15 lbs. The Transfer out is going to Location #2
I don't know how to write the query or set up the group so that it recognizes both the Transfer to and the Transfer From fields
I want the report to look similar to the one below but I can only get it to show one of the locations. Is there some way to use the Union function and have one field in the first table be or equivalent to two fields in another?
Location Code
Item No.
Lbs
Sales Orders
Transfer Out
Transfer In
Available Inventory
Location #1
Product A
15
-15
Location #1
15
-15
Location #2
Product A
15
15
Location #2
15
15Hi Igor,
You can get a custom sort order added to your IP column without the need for a second column.
Consider that the sorting is done strictly left-to-right across a string in the column. The string can be any valid HTML content. So, you could wrap your string within, say, a SPAN tag and add an attribute to that tag that contains the sort order you need before the text that is displayed to the user. As long as the attribute is correctly structured (that is, all instances are of the same length, for example), then sorting will work correctly. For example:
SELECT
'<span title="' || PAD_IP_ADDRESS(IP) || '">' || IP || '</span>' Y
FROM ...Now you need to ensure that the PAD_IP_ADDRESS() function returns the correct values. In IP addresses, you have anything from "0.0.0.0" to "255.255.255.255". To get them to sort "numerically", you need to pad one or two digit numbers to get three digit numbers for each value - so, "0.0.0.0" becomes "000.000.000.000". You could create a function to do this - something like:
CREATE OR REPLACE FUNCTION PAD_IP_ADDRESS
pIP IN VARCHAR2
RETURN VARCHAR2
IS
vIP VARCHAR2(15);
vTEMP APEX_APPLICATION_GLOBAL.VC_ARR2;
vSEP VARCHAR2(1);
BEGIN
vSEP := '';
vIP := '';
vTEMP := APEX_UTIL.STRING_TO_TABLE(pIP,'.');
FOR x IN 1..vTEMP.COUNT
LOOP
vIP := vIP || vSEP || TRIM(TO_CHAR(TO_NUMBER(vTEMP(x)),'000'));
vSEP := '.';
END LOOP;
RETURN vIP;
END;The output from this would look something like:
<span title="001.001.001.001">1.1.1.1</span>
<span title="002.255.255.255">2.255.255.255</span>
<span title="010.001.199.098">10.1.199.098</span>Andy -
OAF Export button fetching data in one column - view object using union all
Dear All,
Export button showing data in one column from view object,
View object is based on mulitple queries with union all ,
Please let me know the solution for this issue.
Thanks
Maheswara RajuMaheswara Raju,
As per my understanding you are not able to export all the View Attribute using export Button. Only the attribute which is used with the item/region will get exported.
There are few work around in case if you want to export the column without showing on OAF Page. Let me know.
Cheers
Gyan
Maybe you are looking for
-
Implicit and Explicit Enhancement
Hi Gurus , Can anyone please let me know about what is implicit enhancement and explicit enhancement.Steps involved in the same . Thanks ... ashok...
-
Change in Scheduling agreement condition value
Hi Friends i have a scheduling agreement with a CVD condition maintained as 10%. the SA is not yet closed and the CVD value has to be changed to 8%. i cant update the value as it is not coming from condition record. cant delete the material line item
-
Deployed four 2960X switches in a stack. All okay for about one month then tried to web browse for the first time via firefox which partially displayed the page. I assumed this was a browser error. So tried Chrome then IE which both failed. Chrom
-
Accessing "globals" from 2 different executables
For an application we need to access the same set of "globals" from 2 different executables. How can this be done?
-
ITunes corrupting video files on metadata changes
I have some video tutorials that I've been attempting to add to my iTunes library so I can watch them on my iPhone and appleTV. The videos copy into my library successfully. They play fine on my mac / phone / aTV as long as I don't change any metadat