Need help in writing SQL query
Hi,
I have a rquirement where I need to convert columns into records.
Table1:
(note: I have around 150 columns i.e period1 to period150)
unit startdate Period1 period2 period3 period4 period5
A 1/1/2011 100 200 300 400 500
Now I need data in below format
UNIT startdate period
A 1/1/2011 100
A 1/1/2011 200
A 1/1/2011 300
A 1/1/2011 500
Please suggest me...
Thanks.
With UNPIVOT you can "name" each of your rows using as.
One trick is to "name" the rows to a number - then you can add that number of weeks to your start date - like this:
with t as (
select 'A' unit, DATE '2011-01-01' startdate, 100 period1, 200 period2 ,300 period3, 400 period4 ,500 period5 from dual
select
unit,
startdate + numtodsinterval(week*7,'day') startdate,
qty
from t
unpivot(
qty for week in (
period1 as 0,
period2 as 1,
period3 as 2,
period4 as 3,
period5 as 4
;Theoretically the above should work - but somehow I get a NULL date on my 11.1 instance? And I don't have another version to test with, alas.
But try it and see if it works on your instance ;-)
Similar Messages
-
Hi Friends,
I am trying to load Employees and their Assignments using APIs.
I have various columns in my staging table like Last Name, First Name, etc., but I need help in writing query in the cursor especially for columns Emp Number and Supervisor Number.
I have data as below
Emp_Number Supervisor_Number
GE0002 GE0064
GE0064 EG0009
EG0009 EG0001
100009 EG0001
EG0001 TU0001
Cursor I write will process the data in the same order as above, but here the problem is...
When it processes first row, it checks for supervisor GE0064 which do not exist and so it errors out.
Similarly for second row, it checks for supervisor EG0009 which again do not exist and so it errors out.
So in order to prevent this, the cursor should process the rows as below
Emp_Number Supervisor_Number
EG0001 TU0001
EG0009 EG0001
GE0064 EG0009
GE0002 GE0064
100009 EG0001
By this way, Supervisor should be defined first as an employee and then it can be used as a supervisor for other employees
is there a way that I can get the output as above(second set of data), when the table has records randomly as above(first set of data)
Appreciate your help!
Thanks,
SrikanthSrikanth wrote:
... but the number of records returned by above query are lot more than number of records in the table.
Why did the number go up?
It's something only you can find out
Maybe some Emp have several Supervisor(s) like
with
t as
(select 'GE0002' Emp,'GE0064' Supervisor from dual union all
select 'GE0064','EG0009' from dual union all
select 'EG0009','EG0001' from dual union all
select 'GE0064','100009' from dual union all
select '100009','EG0001' from dual union all
select 'EG0001','TU0001' from dual
select Emp,Supervisor,lpad('_',3 * (level - 1),'_')||Emp indent
from (select Emp,Supervisor
from t
union all
select supervisor,null
from t tt
where not exists(select null
from t
where emp = tt.supervisor
start with Supervisor is null
connect by prior Emp = Supervisor
EMP
SUPERVISOR
INDENT
TU0001
TU0001
EG0001
TU0001
___EG0001
100009
EG0001
______100009
GE0064
100009
_________GE0064
GE0002
GE0064
____________GE0002
EG0009
EG0001
______EG0009
GE0064
EG0009
_________GE0064
GE0002
GE0064
____________GE0002
Regards
Etbin -
Need help with writing a query with dynamic FROM clause
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
Any pointers will be appreciated.
Thanks
rogers42Hi,
rogers42 wrote:
Hi Folks,
I need help with an query that should generate the "FROM" clause dynamically.
My main query is as follows
select DT_SKEY, count(*)
from *???*
where DT_SKEY between 20110601 and 20110719
group by DT_SKEY
having count(*) = 0
order by 1; The "from" clause of the above query should be generated as below
select 'Schema_Name'||'.'||TABLE_NAME
from dba_tables
where OWNER = 'Schema_Name'
Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
-- Preliminary Query:
COLUMN my_table_name_col NEW_VALUE my_table_name
SELECT table_name AS my_table_name_col
FROM all_tables
WHERE owner = 'SCOTT'
AND table_name LIKE 'E%';
-- Main Query:
SELECT COUNT (*) AS cnt
FROM scott.&my_table_name
;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
Edited by: Frank Kulash on Aug 11, 2011 2:30 PM -
Newbie - need help with a SQL query for a bar chart
Hi,
I'm a new user on APEX with no real SQL knowledge and I'm trying to build a dashboard with charts into an existing APEX application. Based on another application, I have come up with the following SQL code:
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORY
Order by COUNT(PROJECT_ID) DESC
The code from the other app was:
select null link
, FUNCTIONAL_AREA label
, count (decode(PROJECT_STATUS,'Active',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'Complete',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'On Hold',PROJECT_ID)) "On Hold"
, count (decode(PROJECT_STATUS,'Recurring',PROJECT_ID))"Recurring"
, count (decode(PROJECT_STATUS,'Pipeline',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'Not Approved',PROJECT_ID))"Not Approved"
from PM_V2
where LOB='S2S' and (FUNCTIONAL_AREA='Accounts Payable' or FUNCTIONAL_AREA='Expense' or FUNCTIONAL_AREA='Procurement' or FUNCTIONAL_AREA='Fixed Assets')
group by FUNCTIONAL_AREA
Order by COUNT(PROJECT_ID) DESC
I'm getting a "Failed to parse SQL query!" error when I try to run validation.
Is this enough info for some assistance? Any help would really be appreciated.
Thanks,
RachelHello,
This is more of an SQL question, rather than specifically APEX-related. It's notable that you say: I'm a new user on APEX with no real SQL knowledgeWhich is fine (we all have to start somewhere, afterall) but it might be worth de-coupling the problem from APEX in the first instance. I'd also strongly recommend either taking a course, reading a book (e.g. http://books.google.co.uk/books?id=r5vbGgz7TFsC&printsec=frontcover&dq=Mastering+Oracle+SQL&hl=en#v=onepage&q=Mastering%20Oracle%20SQL&f=false) or looking for a basic SQL tutorial - it will save you a whole lot of heartache, I promise you. Search the oracle forums for the terms "Basic SQL Tutorial" and you should come up with a bunch of results.
Given that you've copied your query template from another, I would suggest ensuring that the actual query works first of all. Try running it in either:
* SQL Editor
* SQL*Plus
* an IDE like SQL Developer (available free from the OTN: http://www.oracle.com/technetwork/developer-tools/sql-developer/downloads/index.html ) or TOAD or similar.
You may find there are syntax errors associated with the query - it's difficult to tell without looking at your data model.
select null link
, CATEGORY label
, count (decode(PROJECT_STATUS,'1',PROJECT_ID))"Active"
, count (decode(PROJECT_STATUS,'2',PROJECT_ID))"Complete"
, count (decode(PROJECT_STATUS,'3',PROJECT_ID))"On Hold"
, count (decode(PROJECT_STATUS,'4',PROJECT_ID))"Pipeline"
, count (decode(PROJECT_STATUS,'5',PROJECT_ID))"Pending Review"
from GRAPO_PROHEADTRK
where (PROJECT_STATUS='1' or PROJECT_STATUS='2' or PROJECT_STATUS='3' or PROJECT_STATUS='4' or PROJECT_STATUS='5' or PROJECT_STATUS='6')
group by CATEGORYNote that your "order by" clause references a field called "PROJECT_ID", which exists in the old query but you've changed other similar references to "PROJECT_STATUS" - is it possible you've just missed this one? The perils of copy-paste coding I'm afraid... -
Hi team,
Please help me on below query,
I have table like given below
Tran_Id tran_date amount. Actorid
1. 10-apr-15. 100. 1
2. 11-apr-15. 100. 1
3. 11-apr-15. 900. 1
4. 12-apr-15. 100. 1
5. 13-apr-15. 350. 1
6. 14-apr-15. 400. 1
Now please find the query,
I want all the actor ids whos tran amount
>1500 and the date when the tran amount
Has breached
Ex:
Actor-id. Breached-date. Total
1. 13-apr-15. 1900
How can I write a query for above requirement?
Regards,
RajendraYour solution (same as Saubhik's) is incorrect. Look at source data - multiple transactions can occur same day. Therefore, your qury will return wrong results if breached amount is 1000:
with trans as (
select 1 tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date, 100 amount, 1 actorid from dual union all
select 2, to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
select 3, to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
select 4, to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
select 5, to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
select 6, to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
select 7, to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
select 8, to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
select 9, to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
select 10, to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
trans_running_tot as (
select tran_id, tran_date,
sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
from trans
trans_ranked as (
select actorid,tran_id, tran_date,
rank() over (partition by actorid order by tot_amt) rk
from trans_running_tot
where tot_amt > 1000
select * from trans_ranked where rk=1
ACTORID TRAN_ID TRAN_DATE RK
1 2 11-APR-15 1 -- here total amount was only 200
1 3 11-APR-15 1
2 8 13-APR-15 1
SQL>
As you can see, 2 rows were returned for actor 1. Why? Default for analytic ORDER BY is RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. Therefore, all rows with same transation_date will fall into same window:
SQL> with trans as (
2 select 1 tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date, 100 amount, 1 actorid from dual union all
3 select 2, to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
4 select 3, to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
5 select 4, to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
6 select 5, to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
7 select 6, to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
8 select 7, to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
9 select 8, to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
10 select 9, to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
11 select 10, to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
12 )
13 select tran_id, tran_date,
14 sum(amount) over (partition by actorid order by tran_date) tot_amt, actorid
15 from trans
16 /
TRAN_ID TRAN_DATE TOT_AMT ACTORID
1 10-APR-15 100 1
2 11-APR-15 1100 1
3 11-APR-15 1100 1
4 12-APR-15 1200 1
5 13-APR-15 1550 1
6 14-APR-15 1950 1
7 12-APR-15 300 2
8 13-APR-15 1500 2
9 14-APR-15 1800 2
10 15-APR-15 2100 2
10 rows selected.
SQL>
So correct solution is to ORDER BY transation id. Also, just in case if amount can be 0, we should add tranaction id when ordering by sum:
with trans as (
select 1 tran_Id, to_date('10-apr-15', 'dd-mon-yy') tran_date, 100 amount, 1 actorid from dual union all
select 2, to_date('11-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
select 3, to_date('11-apr-15', 'dd-mon-yy'), 900, 1 from dual union all
select 4, to_date('12-apr-15', 'dd-mon-yy'), 100, 1 from dual union all
select 5, to_date('13-apr-15', 'dd-mon-yy'), 350, 1 from dual union all
select 6, to_date('14-apr-15', 'dd-mon-yy'), 400, 1 from dual union all
select 7, to_date('12-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
select 8, to_date('13-apr-15', 'dd-mon-yy'), 1200, 2 from dual union all
select 9, to_date('14-apr-15', 'dd-mon-yy'), 300, 2 from dual union all
select 10, to_date('15-apr-15', 'dd-mon-yy'), 300, 2 from dual
trans_running_tot as (
select tran_id, tran_date,
sum(amount) over (partition by actorid order by tran_id) tot_amt, actorid
from trans
trans_ranked as (
select actorid,tran_id, tran_date,
rank() over (partition by actorid order by tot_amt,tran_id) rk
from trans_running_tot
where tot_amt > 1000
select * from trans_ranked where rk=1
ACTORID TRAN_ID TRAN_DATE RK
1 3 11-APR-15 1
2 8 13-APR-15 1
SQL>
SY. -
Need help in writing the query
The initial data is as follows:
ID PARENT_ID
=============
1 NULL
2 NULL
3 2
4 6
5 3
6 7
7 4
8 NULL
but output is as follows in such way that Parent_Id should be displayed in ID place
ID PARENT_ID
=============
1 NULL
2 NULL
3 2
8 NULL
6 8
4 6
5 3
7 4
Can any one help how resolve this query?
Thanks in advanceYour output is inconsistent with initial data :) But
select * from t start with parent_id is null connect by parent_id = prior id; -
Hi,
I have a requirement where I need to show 'F&D' string. I can explain this by below query.
select 'F&D' from dual
but when I run this query, toad prompts me to enter value for &D variable :( But my requirement is to show 'F&D' string.
Can anyone please tell me what modification needs to be done to above query to get string 'F&D' as output.
I know work around for this as below.
select 'F'||chr(38)||'D' from dual
I want permenant solution for this. Can anyone please help me?
Thanks
Shantanusee if below make difference
SQL> select 'F&D' from dual ;
Enter value for d: &D
old 1: select 'F&D' from dual
new 1: select 'F&D' from dual
'F&
F&D
SQL> select 'F'||'&'||'D' from dual ;
'F'
F&D -
Need help in writing inline query or subquery
Hi All,
I have 4 select statements like below ,
1>Select customer_number, customer_name,customer_address1
FROM ABC
WHERE Site_use_code='BILL_TO'
2>Select customer_number, customer_name,customer_address1
FROM ABC
WHERE Site_use_code='SHIP_TO'
3>Select customer_number, customer_name,customer_address1
FROM ABC
WHERE Site_use_code='SOLD_TO'
I need to write all these 3 in single select statement in such a way that if any select statement doesnot return any data it should execute the other select statements means it should not fail.
for each column of the select statment i can write separate select statements in that way it should work but the query should be very big.
So please help me on thsi.
ThanksExample of my solution:
SQL> ed
Wrote file afiedt.buf
1 with t as (
2 select 1 as customer_number, 'Fred' as customer_name, 'address1' as customer_address1, 'BILL_TO' as site_use_code from dual union all
3 select 1 as customer_number, 'Fred' as customer_name, 'address1' as customer_address1, 'SHIP_TO' as site_use_code from dual union all
4 select 2 as customer_number, 'Bob' as customer_name, 'address2' as customer_address1, 'BILL_TO' as site_use_code from dual union all
5 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'BILL_TO' as site_use_code from dual union all
6 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'SHIP_TO' as site_use_code from dual union all
7 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'SOLD_TO' as site_use_code from dual union all
8 select 4 as customer_number, 'Tim' as customer_name, 'address4' as customer_address1, 'BILL_TO' as site_use_code from dual union all
9 select 5 as customer_number, 'Sam' as customer_name, 'address5' as customer_address1, 'BILL_TO' as site_use_code from dual
10 )
11 --
12 -- END OF TEST DATA
13 --
14 select customer_number
15 ,customer_name
16 ,customer_address1
17 ,site_use_code
18 from (
19 select customer_number
20 ,customer_name
21 ,customer_address1
22 ,site_use_code
23 ,row_number() over (partition by customer_number order by decode(Site_use_code,'BILL_TO',1,'SHIP_TO',2,3) desc) as rn
24 FROM t
25 WHERE Site_use_code IN ('BILL_TO','SHIP_TO','SOLD_TO')
26 )
27* where rn = 1
SQL> /
CUSTOMER_NUMBER CUSTOM CUSTOMER SITE_US
1 Fred address1 SHIP_TO
2 Bob address2 BILL_TO
3 George address3 SOLD_TO
4 Tim address4 BILL_TO
5 Sam address5 BILL_TO
SQL>Or alternative...
SQL> ed
Wrote file afiedt.buf
1 with t as (
2 select 1 as customer_number, 'Fred' as customer_name, 'address1' as customer_address1, 'BILL_TO' as site_use_code from dual union all
3 select 1 as customer_number, 'Fred' as customer_name, 'address1' as customer_address1, 'SHIP_TO' as site_use_code from dual union all
4 select 2 as customer_number, 'Bob' as customer_name, 'address2' as customer_address1, 'BILL_TO' as site_use_code from dual union all
5 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'BILL_TO' as site_use_code from dual union all
6 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'SHIP_TO' as site_use_code from dual union all
7 select 3 as customer_number, 'George' as customer_name, 'address3' as customer_address1, 'SOLD_TO' as site_use_code from dual union all
8 select 4 as customer_number, 'Tim' as customer_name, 'address4' as customer_address1, 'BILL_TO' as site_use_code from dual union all
9 select 5 as customer_number, 'Sam' as customer_name, 'address5' as customer_address1, 'BILL_TO' as site_use_code from dual
10 )
11 --
12 -- END OF TEST DATA
13 --
14 select distinct
15 customer_number
16 ,customer_name
17 ,customer_address1
18 ,first_value(site_use_code) over (partition by customer_number order by decode(Site_use_code,'BILL_TO',1,'SHIP_TO',2,3) desc) as site_use_code
19 FROM t
20 WHERE Site_use_code IN ('BILL_TO','SHIP_TO','SOLD_TO')
21* order by customer_number
SQL> /
CUSTOMER_NUMBER CUSTOM CUSTOMER SITE_US
1 Fred address1 SHIP_TO
2 Bob address2 BILL_TO
3 George address3 SOLD_TO
4 Tim address4 BILL_TO
5 Sam address5 BILL_TO -
i have a table
source table :
create table order(name_a varchar2(100),intid number);
insert into order values('a',1);
insert into order values('b',1);
insert into order values('c',1);
insert into order values('d',1);
insert into order values('e',2);
insert into order values('f',2);
insert into order values('g',2);
i need a query , which result in the below output :
if i look for intid=1 the query should give a,b,c,d
if i look for intid=2 the query should give f,g
ThanksHi,
781649 wrote:
i have a table
source table :
create table order(name_a varchar2(100),intid number);
insert into order values('a',1);
insert into order values('b',1);
insert into order values('c',1);
insert into order values('d',1);
insert into order values('e',2);
insert into order values('f',2);
insert into order values('g',2);Thanks for posting the CREATE TABLE and INSERT statements; it's very helpful.
i need a query , which result in the below output :
if i look for intid=1 the query should give a,b,c,d
if i look for intid=2 the query should give f,gDid you mean <b>e</b>,f,g ?
That's called String Aggregation , and how to do it depends on your version of Oracle, and your exact requirements.
See thie following page for several techniques:
http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
If you're using Oracle 10 (or higher), and it's important that the name_a's be in order in the output, then you can do this:
WITH got_r_num AS
SELECT name_a
, intid
, ROW_NUMBER () OVER ( PARTITION BY intid
ORDER BY name_a
) AS r_num
FROM order_table -- ORDER is not a good table name
WHERE intid IN (1) -- Optional
SELECT intid
, SUBSTR ( SYS_CONNECT_BY_PATH (name_a, ',')
, 2
) AS name_a_list
FROM got_r_num
WHERE CONNECT_BY_ISLEAF = 1
START WITH r_num = 1
CONNECT BY r_num = PRIOR r_num + 1
AND intid = PRIOR intid
;Starting in Oracle 11.2, LISTAGG is better.
This does not assume that you are getting the output only for a single intid at a time. You can get any number of them in a suingle query. Of course, that number can be 1 if that's what you want.
Edited by: Frank Kulash on Mar 24, 2011 12:19 PM -
Hi evrybody,
I have a requirement which seems very wierd to me, I m unable to clue it also. Please help me in writing the same.
I have a column in a table which contains the data with spaces and everythng same as below:
SUBSCRIBER LINE TEST
VERSION 2
DEV SNB MP FCODE
LIBA-13 4222430012 11 3
FOREIGN VOLTAGE TESTS
DC AC
FVAE FVBE FVAB FVAE FVBE FVAB
LACC LACC 7.4 0.1 0.1 0.1
0.0 0.0 PASS PASS PASS PASS
PASS PASS
INSULATION RESISTANCE TESTS
IRAE IRBE IRABA IRBBA IRAB
LACC LACC LACC LACC 8113K
10000K >10000K >10000K >10000K PASSPASS PASS PASS PASS
CAPACITANCE MEASUREMENTS
CAE CBE CAB BRK
LACC LACC 4428 NO
68 72
NT LOOPBACK TEST
PASS
NT DC SIGNATURE TEST
V-HIGH V-LOW
83.920K LACC
PASS >10000K
PASS
NT CONNECTED
INV
CIRCUIT TEST RESULT
FAIL
I need to get the o/p as:
FVAELACC=0.0 FVBELACC=0.0 FVAB=7.4 FVAE=0.1 FVBE=0.1 FVAB=0.1
CAELACC=68 CBELACC=72 CAB=4428
NT CONNECTED=INV..
Thanks in advance.Evrybody thanks for advices. My Question is little unclear but the requirement is that itself.. Anyways I got the O/p finally.
Mr. Shahzad ,if any of the questions makes u feel like wasting ur technical time, jus donot read it.. The people who can undertsand the problem, they can answer to the post. If the requirement is like that, none of us are helpless. -
Need Help with Advanced SQL Query
It's advanced for me, at least. I have three tables that I
need to use:
Product (product_id and product_title are the fields)
shipRegion (shipRegion_ID)
product_shipRegion_shipCharge (product_id, shipRegion_ID,
primaryShipCharge, secondaryShipCharge)
What I am trying to do is create a query that will look for
two things:
1. Any product that is listed in the
product_shipRegion_shipCharge table that has a primary or secondary
ship charge of $0.00 or is NULL.
That part is easy:
SELECT DISTINCT p.product_id, p.product_title
FROM product p
INNER JOIN product_shipRegion_shipCharge pss ON p.product_id
= pss.product_id AND (pss.primaryShipCharge IS NULL OR
pss.primaryShipCharge = 0 OR pss.secondaryShipCharge IS NULL OR
pss.secondaryShipCharge = 0)
WHERE p.display = 1
AND p.price > 0
It's this next part that's tricky for me:
2. Get the product_id and product_title (from the product
table) that does NOT have any entry in the
product_shipRegion_shipCharge table.
I'm guessing that I need to include some kind of LEFT JOIN in
the above query to find out what all of the regions are (from the
shipRegion table) and then see what's missing for each product in
the product_shipRegion_shipCharge table, but I have no idea how to
do it.
Anyone?
JoshThis should be what the query would look like using the left
join:
SELECT product_table.product_id, product_table.product_title
FROM product_table
LEFT OUTER JOIN product_shipRegion_shipCharge
ON product_shipRegion_shipCharge.product_id =
product_table.product_id
WHERE product_shipRegion_shipCharge. product_id IS NULL
SQL Server's query optimizer will probably turn the '...IN
(subquery)' or '...exists (subquery)' into this kind of execution
plan on its own - depending on your table structures. -
Need help creating large SQL query
I am trying collect the sum of records that have a cancelled event prior to the Arrive event. The solution needs to be within the Sum function. Any ideas would be helpful
The structure of the table is as follows
1. Record_Num(primary): varchar
2. Event_Type: varchar
3. Time: timestamp
Each record number can contain multiple events, hence the issue with specifiying the time for an event of 'Arrive' and an event of 'Canceled'
This is part of a much bigger query, here's what that looks like:
Select
Sum(Case when di.calltype = 'Missed' then 1 else null end) as "Canceled Prior To Liftoff",
Sum(Case
when dt.eventtype = 'Canceled' Then 1
when
(select to_char(dt.datetimestamp, 'HH:MI:SS')
from progpennstar.dispatchtime dt
where Lower(dt.eventtype) in 'aborted')
< any (select to_char(dt.datetimestamp, 'HH:MI:SS')
from progpennstar.dispatchtime dt
where dt.eventtype in 'Arrive Locale')
Then 1
Else null end) as "Canceled Enroute to Call"
From progpennstar.dispatch di, progpennstar.dispatchtime dt
where di.dateoftransport >= to_date('07/01/2008', 'MM/DD/YYYY') and
di.dateoftransport <= to_date('09/30/2008', 'MM/DD/YYYY') and
di.dispatch_id = dt.dispatch_idto the op: I think SomeoneElse already got the solution, I just want to add a few minor points. You can replace the ANY construct (which is rarely used) with a simple comparison. In general ANY constructs are more difficult to understand. Check if the correct logic is applied.
SELECT SUM(CASE
WHEN di.calltype = 'Missed' THEN 1
ELSE NULL
END) AS "Canceled Prior To Liftoff"
,SUM(CASE
WHEN dt.eventtype = 'Canceled' THEN 1
WHEN dt.eventtype = 'Aborted'
AND exists (SELECT null
FROM dispatchtime dt2
WHERE dt2.eventtype IN 'Arrive Locale'
AND dt2.dispatch_id = di.dispatch_id
AND dt.datetimestamp < dt2.datetimestamp /* this is the new comparison */
THEN 1
ELSE NULL
END) AS "Canceled Enroute to Call"
FROM dispatch di,
dispatchtime dt
WHERE di.dateoftransport >= to_date('07/01/2008', 'MM/DD/YYYY')
AND di.dateoftransport < to_date('09/30/2008', 'MM/DD/YYYY') /* Carefull! I changed <= to <. Do you want to include the full last day or only midnight? */
AND di.dispatch_id = dt.dispatch_id;I also changed the alias of the remaining subquery so that different aliases are used.
Edited by: Sven W. on Dec 11, 2008 1:01 PM -
Need helping making a SQL query faster
Below is my query, it takes about 75 seconds to run right now. The outer joins are for cases that do not have records in that table. I am almost completely self taught, so I have some gaps in my knowledge of SQL.
Thanks in advance for your help.
SELECT DISTINCT B1.B1_ALT_ID CASENUMBER,
B1.B1_PER_GROUP
||'/'
||B1.B1_PER_TYPE
||'/'
||B1.B1_PER_SUB_TYPE
||'/'
||B1.B1_PER_CATEGORY APPTYPE,
BPD.B1_COMPLETE_BY RECBY,
BPD.HOUSE_COUNT HOUSECOUNT,
BPD.REC_DATE,
CASE
WHEN B3C.B1_BUS_NAME IS NOT NULL
AND B3C.B1_PRINT_FLAG = 'Y' THEN B3C.B1_BUS_NAME
ELSE B3O.B1_OWNER_FULL_NAME
END CONTRACTOR,
B3O.B1_OWNER_FULL_NAME OWNERNAME,
B3O.B1_MAIL_ADDRESS1,
B3O.B1_MAIL_ADDRESS2,
B3O.B1_MAIL_ADDRESS3,
B3O.B1_MAIL_CITY,
B3O.B1_MAIL_STATE,
B3O.B1_MAIL_ZIP,
FN_GET_PRI_ADDRESS_PARTIAL('RENO',B1.B1_PER_ID1,B1.B1_PER_ID2,B1.B1_PER_ID3) JOBSITE,
B3P.B1_PARCEL_NBR PARCELNUMBER,
B3P.B1_LOT LOT,
BV.G3_VALUE_TTL JOBVALUE,
BW.B1_WORK_DESC WORKDESC,
CASE
WHEN B3CON.B1_BUSINESS_NAME IS NOT NULL
AND B3CON.B1_CONTACT_TYPE = 'Occupant/Tenant' THEN B3CON.B1_BUSINESS_NAME
WHEN B3CON.B1_BUSINESS_NAME IS NULL
AND B3CON.B1_CONTACT_TYPE = 'Occupant/Tenant' THEN B3CON.B1_FNAME
||' '
||B3CON.B1_LNAME
ELSE ''
END TENANT,
(SELECT DISTINCT BAV.ATTRIBUTE_VALUE
FROM BAPPSPECTABLE_VALUE BAV
WHERE B1.B1_PER_ID1 = BAV.B1_PER_ID1
AND B1.B1_PER_ID2 = BAV.B1_PER_ID2
AND B1.B1_PER_ID3 = BAV.B1_PER_ID3
AND BAV.COLUMN_NAME = 'Type of Construction') TOC,
(SELECT DISTINCT BAV.ATTRIBUTE_VALUE
FROM BAPPSPECTABLE_VALUE BAV
WHERE B1.B1_PER_ID1 = BAV.B1_PER_ID1
AND B1.B1_PER_ID2 = BAV.B1_PER_ID2
AND B1.B1_PER_ID3 = BAV.B1_PER_ID3
AND BAV.COLUMN_NAME = 'Occupancy Group') OCCGROUP,
(SELECT DISTINCT BAV.ATTRIBUTE_VALUE
FROM BAPPSPECTABLE_VALUE BAV
WHERE B1.B1_PER_ID1 = BAV.B1_PER_ID1
AND B1.B1_PER_ID2 = BAV.B1_PER_ID2
AND B1.B1_PER_ID3 = BAV.B1_PER_ID3
AND BAV.COLUMN_NAME = 'Occupancy Use') OCCUSE,
(SELECT DISTINCT BC.B1_CHECKLIST_COMMENT
FROM BCHCKBOX BC
WHERE B1.B1_PER_ID1 = BC.B1_PER_ID1
AND B1.B1_PER_ID2 = BC.B1_PER_ID2
AND B1.B1_PER_ID3 = BC.B1_PER_ID3
AND BC.B1_CHECKLIST_COMMENT IS NOT NULL
AND BC.B1_CHECKBOX_DESC = 'Fire Alarm System') FIREALARM,
(SELECT DISTINCT BC.B1_CHECKLIST_COMMENT
FROM BCHCKBOX BC
WHERE B1.B1_PER_ID1 = BC.B1_PER_ID1
AND B1.B1_PER_ID2 = BC.B1_PER_ID2
AND B1.B1_PER_ID3 = BC.B1_PER_ID3
AND BC.B1_CHECKLIST_COMMENT IS NOT NULL
AND BC.B1_CHECKBOX_DESC = 'Fire Sprinkler System') FIRESPRINKLER
FROM B1PERMIT B1
INNER JOIN BPERMIT_DETAIL BPD
ON B1.B1_PER_ID1 = BPD.B1_PER_ID1
AND B1.B1_PER_ID2 = BPD.B1_PER_ID2
AND B1.B1_PER_ID3 = BPD.B1_PER_ID3
LEFT OUTER JOIN B3CONTRA B3C
ON B1.B1_PER_ID1 = B3C.B1_PER_ID1
AND B1.B1_PER_ID2 = B3C.B1_PER_ID2
AND B1.B1_PER_ID3 = B3C.B1_PER_ID3
AND B3C.B1_PRINT_FLAG = 'Y'
LEFT OUTER JOIN B3OWNERS B3O
ON B1.B1_PER_ID1 = B3O.B1_PER_ID1
AND B1.B1_PER_ID2 = B3O.B1_PER_ID2
AND B1.B1_PER_ID3 = B3O.B1_PER_ID3
and b3o.b1_primary_owner = 'Y'
LEFT OUTER JOIN B3PARCEL B3P
ON B1.B1_PER_ID1 = B3P.B1_PER_ID1
AND B1.B1_PER_ID2 = B3P.B1_PER_ID2
AND B1.B1_PER_ID3 = B3P.B1_PER_ID3
INNER JOIN BVALUATN BV
ON B1.B1_PER_ID1 = BV.B1_PER_ID1
AND B1.B1_PER_ID2 = BV.B1_PER_ID2
AND B1.B1_PER_ID3 = BV.B1_PER_ID3
INNER JOIN BWORKDES BW
ON B1.B1_PER_ID1 = BW.B1_PER_ID1
AND B1.B1_PER_ID2 = BW.B1_PER_ID2
AND B1.B1_PER_ID3 = BW.B1_PER_ID3
LEFT OUTER JOIN B3CONTACT B3CON
ON B1.B1_PER_ID1 = B3CON.B1_PER_ID1
AND B1.B1_PER_ID2 = B3CON.B1_PER_ID2
AND B1.B1_PER_ID3 = B3CON.B1_PER_ID3
AND B3CON.B1_CONTACT_TYPE = 'Occupant/Tenant'
LEFT OUTER JOIN BAPPSPECTABLE_VALUE BAV
ON B1.B1_PER_ID1 = BAV.B1_PER_ID1
AND B1.B1_PER_ID2 = BAV.B1_PER_ID2
AND B1.B1_PER_ID3 = BAV.B1_PER_ID3
AND BAV.COLUMN_NAME IN ('Type of Construction',
'Occupancy Group',
'Occupancy Use')
LEFT OUTER JOIN BCHCKBOX BC
ON B1.B1_PER_ID1 = BC.B1_PER_ID1
AND B1.B1_PER_ID2 = BC.B1_PER_ID2
AND B1.B1_PER_ID3 = BC.B1_PER_ID3
AND BC.B1_CHECKBOX_DESC IN ('Fire Alarm System',
'Fire Sprinkler System')
WHERE B1.B1_ALT_ID = UPPER('{?CaseNumber}')
and rownum = 1Hi James
Please provide me the following information.
1)What is the version of crystal reports you are using?
2)Whcih database & connection type are you using?
3)Does this query take 75 mins to run in Crystal reports designer?
4)How much time does it take at your database end?
5)How many records are fetched by this query?
6)Looking at the query it shows that it is using case statements and few joins for restricting the data.
7)Please use the same query in a command object in Crystal reports designer and check the result.
Thanks
Pradeep Hulke -
Hi,
I have a table with two columns as follows
child parent
mom grandma
daughter mom
How can I write a single query so that the result will be daughter,mom,grandma?
Thanks
Ravi.Responses to these postings will help:
pivot the column names
PIVOT in oracle.
Re: Pivot Query -
SQL Gurus : Need Help in building SQL query
SQL Gurus,
Need your expertise to solve my below problem:
- I have a column that had comma separated data, basically there are the levels in a hierarchy. eg The same column could have the following data:
Row 1: R1L1, R1L2, R1L3
Row 2: R2L1, R2L2
Row 3: R3L1, R3L2, R3L3, R3L4
For assumption purpose lets assume that there are maximum 5 Levels
I want to put this data from this column into another table which holds the levels. I am expecting the output in another table as follows:
Col1____Col2 ____Col3____Col4____Col5
Row 1: R1L1___R1L2____R1L3____null_____null
Row 2: R2L1___R2L2____null_____null_____null
Row 3: R3L1___R3L2____R3L3____R3L4___null
How do i achieve this ? ie coverting the comma separated values in a column to separate columns. The # of values in each columns could be different as I have showb above
Regards,
pkwith t as (
select 'R1L1, R1L2, R1L3' c1 from dual union all
select 'R2L1, R2L2' c1 from dual union all
select 'R3L1, R3L2, R3L3, R3L4' c1 from dual
select substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l + 1,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1) - 2) col1,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1) - 2) col2,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 1,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1) - 2) col3,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 2,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1) - 2) col4,
substr(c1,instr(', ' || c1 || ', ',', ',1,mod(l - 4,5) + 1),instr(', ' || c1 || ', ',', ',1,mod(l - 3,5) + 1) - instr(', ' || c1 || ', ',', ',1,mod(l - 4,5) + 1) - 2) col5
from (
select c1,
length(c1) - length(replace(c1,',')) + 5 l
from t
COL1 COL2 COL3 COL4 COL5
R1L3 R1L2 R1L1
R2L2 R2L1
R3L4 R3L3 R3L2 R3L1
SQL> SY.
Maybe you are looking for
-
Can't find video setting.....
I am trying to play a video podcast. My Ipod Nano (5G) says TV Out Enabled Normally I would go to Video > Settings BUT..... I now go to Video and it says "No Videos - You can sync videos from ITunes" and doesn't give me access to the video settings o
-
Restrict the hours to be integer in timesheet
While submitting timesheet, can I restrict that the user must input hours in integer without digits? Thanks. Kevin Li
-
After Mountain Lion, iMac goes to sleep even while Quicktime is converting files
Hello! After Mountian Lion, I have had to change my Energy setting to NEVER put the computer to sleep. iMac has been going to sleep even while it is converting files. This never happened with the previous OSX. Does anyone know why it goes to sleep ev
-
Writing CMP Finder SQL Syntax?
What is the syntax for writing the finder SQL for CMP? From the CMP sample code for the OAS it looks like it might be &fieldname <op> $1 (for the first parameter?)? Joe McDaniel
-
Hi I am playing out an HD sequenece at 23.98psf on to a hdcam sr deck from fcp 6.0.1. Although the timecode of the first frame on the sequence drops in at the correct tc on the tape, the end frame is one frame late. This drift seems to occur somewher