Sql forum or help with sql query
I am trying to work on joining two tables. The part that has thrown me for a loop is that the two tables don't have one unique item that makes a row unique. It is accomplished by using several rows. Suppose I have tableOne and tableTwo. On a unique index tableOne has the columnns tableOne.colA tableOne.colB tableOne.colC and tableOne.colD
in tableTwo there is the following tables in it's unique index.
tableTwo.colA, tableTwo.colB and tableTwo.colC.
I have been trying something like the following :
Select tableTwo.ColA, tableTwo.Colx, tableTwo.colY from tableOne inner join tableTwo on tableOne.ColA=tableTwo.colA and tableOne.ColB=tabletwo.ColB and tableOne.ColC=tableTwo.colC where tableOne.colA='value'
Any suggestions or thoughts ?
thanks in advance for looking at it. If any clarification or further information is required please let me know.
The question is how to join using two or more
columns?
select m.F1, n.F2
from table1 m, table2 n
where m.F1 = n.F1 and m.F3 = n.F4
Table aliases (m and n) make the field names unique.Two parts to it the first part is yes joining on multiple columns, but the second part is also having those values match a third value.
Basically I want to get the rows out of tables A and B where A.F1 = B.F1 ='value'
where value is a parameter passed into the preparedStatement.
Please correct me if I am wrong but I would have thought that putting A.F1 = B.F1 would have uniquely identified each column as belonging to that particular table (the tables being compared are not identical).
Similar Messages
-
Need urgent help with the query - Beginer
Hello - I need help with a query to populate data in a table.Here is the scenario.
Source1
MnthID BranchCod CustID SegCode FXStatus ProfStatus Profit
200712 B1 C1 20 Y Y 100
Source2
MnthID BranchCod CustID ProdCode ProdIndex
200712 B1 C1 12 1
200712 B1 C2 12 0
Destination
MnthID BranchCod SegCode ProdCode CountSegCust CountProdCust ProfitProdCust
Condition and Calculations:
1)Source1 customer are base customers.If Source2 has customers who is not in source1 then that customer's record should not be fetched.
2)SegCode, FX Status, ProfStatus is one variable in destination table. [ SegCode = SegCode+ FXStatus (if FXStatus = Y)+ ProfStatus (if FXStatus = Y) ]
3)CountSegCust = CountCustID Groupby MnthID,BranchCod,SegCode Only.
4)CountProdCust = CountCustID Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
5)ProfitProdCust = Sum of Profit of Customers Groupby MnthID,BranchCod,SegCode,ProdCode (when ProdIndex = 1)
Apologies for bad formatting.
Thanks in advance!!A total guess indeed.
It's not clear whether some aggregation can be done (summing counts of grouped data might cause some customers being counted more than once)
insert into destination
select mnthid,branchcod,segcode,prodcode,countsegcust,countprodcust,profitprodcust
from (select s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end segcode,
s2.prodcode,
count(s1.custid) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
order by null
) countsegcust,
count(case proindex when 1
then custid
end
) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) countprodcust,
sum(case proindex when 1
then profit
end
) over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) profitprodcust,
row_number() over (partition by s1.mnthid,
s1.branchcod,
s1.segcode || case s1.fxstatus when 'Y' then s1.fxstatus || s1.profstatus end
s2.prodcode
order by null
) the_row
from source1 s1,source2 s2
where s1.mnthid = s2.mnthid
and s1.branchcod = s2.branchcod
and s1.custid = s2.custid
where the_row = 1Regards
Etbin -
Please, need help with a query
Hi !
Please need help with this query:
Needs to show (in cases of more than 1 loan offer) the latest create_date one time.
Meaning, In cases the USER_ID, LOAN_ID, CREATE_DATE are the same need to show only the latest, Thanks!!!
select distinct a.id,
create_date,
a.loanid,
a.rate,
a.pays,
a.gracetime,
a.emailtosend,
d.first_name,
d.last_name,
a.user_id
from CLAL_LOANCALC_DET a,
loan_Calculator b,
bv_user_profile c,
bv_mr_user_profile d
where b.loanid = a.loanid
and c.NET_USER_NO = a.resp_id
and d.user_id = c.user_id
and a.is_partner is null
and a.create_date between
TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
order by a.create_dateTake a look on the syntax :
max(...) keep (dense_rank last order by ...)
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions056.htm#i1000901
Nicolas. -
Please need help with this query
Hi !
Please need help with this query:
Needs to show (in cases of more than 1 loan offer) the latest create_date one time.
Meaning, In cases the USER_ID, LOAN_ID, CREATE_DATE are the same need to show only the latest, Thanks!!!
select distinct a.id,
create_date,
a.loanid,
a.rate,
a.pays,
a.gracetime,
a.emailtosend,
d.first_name,
d.last_name,
a.user_id
from CLAL_LOANCALC_DET a,
loan_Calculator b,
bv_user_profile c,
bv_mr_user_profile d
where b.loanid = a.loanid
and c.NET_USER_NO = a.resp_id
and d.user_id = c.user_id
and a.is_partner is null
and a.create_date between
TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
order by a.create_datePerhaps something like this...
select id, create_date, loanid, rate, pays, gracetime, emailtosend, first_name, last_name, user_id
from (
select distinct a.id,
create_date,
a.loanid,
a.rate,
a.pays,
a.gracetime,
a.emailtosend,
d.first_name,
d.last_name,
a.user_id,
max(create_date) over (partition by a.user_id, a.loadid) as max_create_date
from CLAL_LOANCALC_DET a,
loan_Calculator b,
bv_user_profile c,
bv_mr_user_profile d
where b.loanid = a.loanid
and c.NET_USER_NO = a.resp_id
and d.user_id = c.user_id
and a.is_partner is null
and a.create_date between
TO_DATE('6/3/2008 01:00:00', 'DD/MM/YY HH24:MI:SS') and
TO_DATE('27/3/2008 23:59:00', 'DD/MM/YY HH24:MI:SS')
where create_date = max_create_date
order by create_date -
I created a blogging tool for my students to use as I teach
them internet safety and cyber citizenship. I am no CF master, but
I dabble a little bit here and there. I need some help with this
query. It is running extremely slow, which means I have probably
created some horrendous loop in this query. If any one out there
has a better solution for this query, I and my middle school
students would be extremely grateful.
Here's what I would like it to do. I have two tables, one for
the blog messages and another for comments. The comments are linked
to their respective blog messages through a common database field.
When someone clicks on a link to read a student's blog, a query
runs which pulls all of the blog messages for that user, the
comments, and it also counts the number of comments entries for
each message so that I can place a total # of comments under each
blog message.Not sure why you have this like this: (Select
count(commentid) from comments where comments.blogid = blog.blogid)
or this twice: blog.blogusersid = #fname#
You need to make sure that the comments.blogid and
blog.blogid fields are indexed. Does this query work any faster?
<cfquery Name="Myblog" datasource="blog">
SELECT b.blogid, b.btitle, b.bcontent, b.bdate,
b.blogusersid, b.fname, b.lname, b.blogpict, b.pictlocation,
b.userid, c.commentid, c.blogid, b.lastupdated, COUNT(c.commentid)
AS cc
FROM blog AS b
INNER JOIN comments AS c ON c.blogid = b.blogid
WHERE b.blogusersid = #fname#
GROUP BY b.blogid, b.btitle, b.bcontent, b.bdate,
b.blogusersid, b.fname, b.lname, b.blogpict, b.pictlocation,
b.userid, c.commentid, c.blogid, b.lastupdated
ORDER BY b.bdate
</cfquery>
..... but I'm not sure that you will be getting the comment
count that you want with either query.
Phil -
Hi guys can someone help with a query regarding the 'podcast app' why do they not have all the episodes that relate to one show available why only half or a selected amount
THanks...but some days they have all the episodes right back to the very first show...ive downloaded a few but they are only available every now and then which makes no sense...why not have them available the whole time ??
-
Hello all,
Total newbie to this pl/sql stuff. So, deseperately need help in my query.
BOOKING_ID BOOKING_STATUS BOOKING_DATE BOOKING_TIME BOOKING_DATE_TIME
1234567 CANCELLED 20090301 37252 5/1/2010 10:20
1234567 CANCELLED 20090301 44229 5/1/2010 12:17
1234567 BOOKED 20090301 39462 5/1/2010 10:57
1234567 CANCELLED 20090301 43549 5/1/2010 12:05
9671111 BOOKED 20090301 68124 5/1/2010 12:57
9671111 CANCELLED 20090301 45001 5/1/2010 12:05
How do I write my query such that I would get the following results:
BOOKING_ID BOOKING_STATUS BOOKING_DATE BOOKING_TIME BOOKING_DATE_TIME
9671111 BOOKED 20090301 68124 2/4/2010 12:17
Basically, I am looking at the latest BOOKING_TIME and making sure the BOOKING_STATUS=BOOKED, if not, don't even bother bring back the result. Hence, you see that BOOKING_ID=1234567 is not required since at the latest BOOKING_TIME=44229, the BOOKING_STATUS=CANCELLED.
Any help is greatly appreciated.
Thank you in advance for your help.
Stanley HoHi, Stanley,
Welcome to the forum!
Whenever you have a question, please post your sample data in a form that people can actually use. CREATE TABLE and INSERT statements are perfect.
For example:
CREATE TABLE booking
( booking_id NUMBER (8)
, booking_status VARCHAR2 (10)
, booking_date_time DATE
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 10:20', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 12:17', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'BOOKED', TO_DATE ('5/1/2010 10:57', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (1234567, 'CANCELLED', TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (9671111, 'BOOKED', TO_DATE ('5/1/2010 12:57', 'MM/DD/YYYY HH24:MI'));
INSERT INTO booking (booking_id, booking_status, booking_date_time)
VALUES (9671111, 'CANCELLED', TO_DATE ('5/1/2010 12:05', 'MM/DD/YYYY HH24:MI'));What you want is called a Top-N Query .
Here's one way to do it:
WITH got_rnum AS
SELECT booking.*
, ROW_NUMBER () OVER ( PARTITION BY booking_id
ORDER BY booking_date_time DESC
) AS rnum
FROM booking
SELECT booking_id
, booking_status
, TO_CHAR (booking_date_time, 'YYYYMMDD') AS booking_date
, TO_CHAR (booking_date_time, 'SSSSS') AS booking_time
, TO_CHAR (booking_date_time, 'MM/DD/YYYY HH24:MI') AS booking_date_time
FROM got_rnum
WHERE rnum = 1
AND booking_status = 'BOOKED'
;Notice that you don't need PL/SQL to do this; plain old SQL is good enough.
Of course, if you're using PL/SQL for other reasons, you can use a query like this within PL/SQL.
Dates (including time of day) should always be stored in DATE columns.
If you have a DATE column, like booking_date_time, then there's no need for redundant date and time columns.
You can always display just the year-month-day, or just the time, in any format, as I did above.
The output from the query above, with the data above, is:
BOOKING_ID BOOKING_ST BOOKING_ BOOKI BOOKING_DATE_TIM
9671111 BOOKED 20100501 46620 05/01/2010 12:57I realize the booking_date and booking_time columns aren't quite what you posted. If they are not derivable from booking_date_time, then you probably do need separate columns for them, and those columns can easily be added to the query above.
Edited by: Frank Kulash on Feb 5, 2010 4:41 PM
KEEP (DENSE_RANK ...) , like Max used below, is a great tool to have in your kit. The problem with it is that you have to repeat a lot of stuff for every column, so the more columns you have in your output, the more tedious it gets. ROW_NUMBER sclaes much better, and is adaptable to more situations. I suggest you master ROW_NUMBER first, and look into KEEP (DENSE_RANK ...) later. -
Help with aging query. not sure how to acomplish this???
Guys im a bit stuck usually i have a slight idea how to even start my query but for this particular one I just dont even know where to start to tackle
i have a table like so.
create table TRRACCD (
TRRACCD_GRNT_CODE varchar2(6),
TRRACCD_TRANS_dATE date,
TRRACCD_AMOUNT number(17,2),
trraccd_detail_code varchar2(6))with data like so
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('15-FEB-10', 'DD-MM-RR'),19764.77,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('12-MAR-10', 'DD-MM-RR'),2054.29,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('20-APR-10', 'DD-MM-RR'),4111.46,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('14-MAY-10', 'DD-MM-RR'),2570.1,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('10-JUN-10', 'DD-MM-RR'),2176.16,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('12-JUL-10', 'DD-MM-RR'),4756.29,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('13-AUG-10', 'DD-MM-RR'),28500.62,'GCSH');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('16-AUG-10', 'DD-MM-RR'),3602.3,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('17-SEP-10', 'DD-MM-RR'),3995.79,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('11-OCT-10', 'DD-MM-RR'),3413.6,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('11-NOV-10', 'DD-MM-RR'),2119.86,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('10-DEC-10', 'DD-MM-RR'),5905.52,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('10-DEC-10', 'DD-MM-RR'),12008.21,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('11-JAN-11', 'DD-MM-RR'),-10574.05,'GBIL');
INSERT INTO TRRACCD (TRRACCD_GRNT_CODE, TRRACCD_TRANS_DATE, TRRACCD_AMOUNT, TRRACCD_DETAIL_CODE) VALUES ('400364',to_date('11-JAN-11', 'DD-MM-RR'),20241.9,'GBIL');however what i need to do is end up with an aging for the items summarize so the expected output should be something like
tbrraccd_grnt_Code 30-60 60-90 over90
400364 20,241.90 2119.86 7,370.09
if your confused about how i arrived at the 7370.90 is because i have to subtract entries with GCSH on them and i also need to take
entries that are - and applied them to the oldest period if the balance of the period is positive. im inclined to say that i can do this with sql but the only other way i can think of is using plsql?... any suggestions or solutions would be greatly appreciated.
the closest that i have gotten to acomplishing this query without pl is this. i know is lame but i need help.
SELECT TRRACCD_GRNT_CODE,
TRRACCD_TRANS_dATE,
TRRACCD_AMOUNT,
trraccd_detail_code,
round(sysdate - TRRACCD_TRANS_dATE) "total days"
--sum(case when round(sysdate - TRRACCD_TRANS_dATE)>190 then "greater then 190"end )
FROM TRRACCD
where trraccd_grnt_Code = '400364'
ORDER BY TRRACCD_GRNT_CODE,
TRRACCD_TRANS_dATE,
trraccd_detail_code;Hi, Miguel,
I should have mentioned this before: I'm assuming SYSDATE is some point on January 22, 2011, after 00:00. I don't think this has caused any confusion so far, but if the discussion continues for a day or two, let's be clear about that.
I think I see what you want regarding the rows where trraccd+detailcode='GSCH'. If we completly ignored all the GSCH rows, we would get this output:
TRRACC 0-29 30-59 60-89 90-over
400364 ...
400404 19904.97 6625.27 4757.01 67618.68You want GSCH amounts to cancel other amounts in the last column only until that column reaches 0 ; the remaining GSCH amount will cancel amounts in to "60-89" column, again, only until that amount reaches 0 . If there is anything left over, it will cancel amounts in the "30-59" column, and if there is still some left over, the "0-29" column.
To be specific, trraccd_grnt_code=400404 has a total of 72475.69 from GSCH rows. That counts against the "90-over" total.
67618.68 - 72475.69 = -4757.01; you want to dispaly 0 in the "90-over" column, and apply the remaining 4757.01 to the next column to the left.
That column contains 4757.01, which happens to be the exact maount left over from the previous subtraction, so you want to diesplay 0 in the "60-89" column.
The remaining columns to the left should contain their regular totals.
Here's one way to do that:
WITH got_col_num AS
SELECT trraccd_grnt_code
, CASE
WHEN trraccd_detail_code != 'GCSH' THEN trraccd_amount
END AS net_amount
, SUM ( CASE
WHEN trraccd_detail_code = 'GCSH' THEN trraccd_amount
END
) OVER (PARTITION BY trraccd_grnt_code)
AS gsch_total
, CASE
WHEN trraccd_amount < 0 THEN 4
WHEN trraccd_trans_date > SYSDATE - 30 THEN 1
WHEN trraccd_trans_date > SYSDATE - 60 THEN 2
WHEN trraccd_trans_date > SYSDATE - 90 THEN 3
ELSE 4
END AS col_num
FROM trraccd
WHERE trraccd_trans_date <= SYSDATE
, got_sum AS
SELECT trraccd_grnt_code
, col_num
, LEAST ( SUM (net_amount)
, GREATEST ( 0
, SUM (SUM (net_amount)) OVER ( PARTITION BY trraccd_grnt_code
ORDER BY col_num DESC
- gsch_total
) AS total
FROM got_col_num
GROUP BY trraccd_grnt_code
, col_num
, gsch_total
SELECT trraccd_grnt_code
, SUM (CASE WHEN col_num = 1 THEN total END) AS "0-29"
, SUM (CASE WHEN col_num = 2 THEN total END) AS "30-59"
, SUM (CASE WHEN col_num = 3 THEN total END) AS "60-89"
, SUM (CASE WHEN col_num = 4 THEN total END) AS "90-over"
FROM got_sum
GROUP BY trraccd_grnt_code
ORDER BY trraccd_grnt_code
;Whenever you want to understand a query like this, run just the first sub-query (in this case, got_col_num) and make sure you understand what it's doing. When you do, add one more sub-query, and make sure you understand what it's doing.
Add morte columns to the display to help you understand it better. For example, when you get to the point where you're trying to understand the 2nd sub-query above, got_sum, you might run this query:
WITH got_col_num AS
SELECT trraccd_grnt_code
, CASE
WHEN trraccd_detail_code != 'GCSH' THEN trraccd_amount
END AS net_amount
, SUM ( CASE
WHEN trraccd_detail_code = 'GCSH' THEN trraccd_amount
END
) OVER (PARTITION BY trraccd_grnt_code)
AS gsch_total
, CASE
WHEN trraccd_amount < 0 THEN 4
WHEN trraccd_trans_date > SYSDATE - 30 THEN 1
WHEN trraccd_trans_date > SYSDATE - 60 THEN 2
WHEN trraccd_trans_date > SYSDATE - 90 THEN 3
ELSE 4
END AS col_num
FROM trraccd
WHERE trraccd_trans_date <= SYSDATE
, got_sum AS
SELECT trraccd_grnt_code
, col_num
, gsch_total
, SUM (net_amount) AS period_sum
, SUM (SUM (net_amount)) OVER ( PARTITION BY trraccd_grnt_code
ORDER BY col_num DESC
) AS running_sum
, LEAST ( SUM (net_amount)
, GREATEST ( 0
, SUM (SUM (net_amount)) OVER ( PARTITION BY trraccd_grnt_code
ORDER BY col_num DESC
- gsch_total
) AS total
FROM got_col_num
GROUP BY trraccd_grnt_code
, col_num
, gsch_total
SELECT *
FROM got_sum
ORDER BY trraccd_grnt_code
, col_num
;which produces this output:
TRRACC COL_NUM GSCH_TOTAL PERIOD_SUM RUNNING_SUM TOTAL
400364 1 28500.62 20241.9 76146.2 20241.9
400364 2 28500.62 17913.73 55904.3 17913.73
400364 3 28500.62 2119.86 37990.57 2119.86
400364 4 28500.62 35870.71 35870.71 7370.09
400404 1 72475.69 19904.97 99005.93 19904.97
400404 2 72475.69 6625.27 79100.96 6625.27
400404 3 72475.69 4857.01 72475.69 0
400404 4 72475.69 67618.68 67618.68 0The total column in that sub-query is very complicated, so break it down some. You can see that it is based on an analytic SUM whose argumenet is an aggregate SUM, all wrapped in LEAST and GREATEST. That can be very hard to underrstand, so break it down. Display the aggregate SUM by itself (period_sum) and also display the analytic SUM, without the GREATEST and LEAST.
mlov83 wrote:
where can i get more information about these types of querys?Can you be more specific? What types of queries do you mean? Complicated queries? Pivots? GROUP BY?
... I'm always leary of using a solution that i dont understand Excellent reaction!
would you mind expalining it to me a little.Again, could you be more specific? I don't mind explaining things to you, but I don't want to explain parts you already understand. If something is new, you'll want to read the SQL Language manual, or other sources, anyway, so it's more efficient to do that first, and then post specific questions on this forum.
An example of a more specific question is: "When I looked up "WITH clause" in the SQL Language reference, I found this page:
http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9758
but I don't understand where it says ...
The query above says ... Is that what the manual is talking about when it says ...?"
Another example of a good question is
"The query you posted says ... I don't understand what that's doing. I looked for ... and ... but that didn't seem to have anything to do with this query. What should I look for?
The Oracle 10 SQL Language manual is indexed pretty poorly. If you can't find something, it may not be your fault. -
select * from testme;
NAME VAL
A 1
A 2
A 3
B 1
B 2
B 3
C 1
C 2
I want to get the maximum of name and the maximum of corresponding name's value.
ie., the answer should be
Name VAL
C 2
Please help me with the query.
ThnxSQL> create table testme
2 as
3 select 'A' name, 1 val from dual union all
4 select 'A', 2 from dual union all
5 select 'A', 3 from dual union all
6 select 'B', 1 from dual union all
7 select 'B', 2 from dual union all
8 select 'B', 3 from dual union all
9 select 'C', 1 from dual union all
10 select 'C', 2 from dual
11 /
Tabel is aangemaakt.
SQL> select max(name) name
2 , max(val) keep (dense_rank last order by name) val
3 from testme
4 /
NAME VAL
C 2Regards,
Rob. -
Hello, i am trying to display a line chart, for some sales data.
I want a line (series) for each product, X axis should be the years in the data
(2007, 2008, 2009 there is no more data than these years)
The plan is to eventually use a "Function Returning SQL Query" to get dynamic series.
But i tried to hardcode 2 lines for 2 products first to try it out.
I used this query in SQL Workshop > SQL Commands
to view the data i want and it works correctly
Query1:
SELECT product.major_brand, timeperiod.year, SUM(sales_fact.euro_sales) AS sales
FROM sales_fact
INNER JOIN product ON sales_fact.product_id = product.product_id
INNER JOIN timeperiod ON sales_fact.timeperiod_id = timeperiod.timeperiod_id
GROUP BY product.major_brand, timeperiod.year
ORDER BY product.major_brand, timeperiod.year ASCI have tried the following query for the chart but it will show 2 flat lines
with the value 0 for each year.
Query2:
SELECT NULL
,timeperiod.year
,SUM(decode(product.major_brand, 'BELCINO', sales_fact.euro_sales, 0)) "BELCINO"
,SUM(decode(product.major_brand, 'BIORGANIC', sales_fact.euro_sales, 0)) "BIORGANIC"
FROM sales_fact
INNER JOIN product ON sales_fact.product_id = product.product_id
INNER JOIN timeperiod ON sales_fact.timeperiod_id = timeperiod.timeperiod_id
GROUP BY product.major_brand, timeperiod.yearThanks for reading,
Any help is appreciated!
Edited by: 908157 on 15-jan-2012 5:22
Edited by: 908157 on 15-jan-2012 5:22Thanks Jeff for the quick response,
I have looked at the examples, tried some things
and found out that my GROUP BY was the problem.
Apperantly i only have to GROUP BY on year and not also on product.
I dont fully understand why yet,
i guess the query gets parsed and translated to 2 queries, one for each line, that makes sense
This is the query that worked for me:
SELECT NULL
,t.year
,SUM(decode(p.major_brand, 'BELCINO', s.euro_sales, 0)) "BELCINO"
,SUM(decode(p.major_brand, 'BIORGANIC', s.euro_sales, 0)) "BIORGANIC"
FROM sales_fact s, product p, timeperiod t
WHERE s.product_id = p.product_id
AND s.timeperiod_id = t.timeperiod_id
GROUP BY t.year
ORDER BY t.yearThanks again! -
I need help with SQL query (if it can be accomplished with query at all).
I'm going to create a table with structure similar to:
Article_Name varchar2(30), Author_Name varchar2(30), Position varchar2(2). Position field is basicly position of an article author in the author list, e.g. if there is one author, his/her position is 0, if 2, then 1st author is 0, second is 1, etc.
Article_Name Author_Name Position
Outer Space Smith 0
Outer Space Blake 1
How can I automate creation of Position, based on number of authors on the fly? Let's say I have original table without Position, but I want to create a new table that will have this information.
RegardsIf you have an existing table whose structure doesn't tell you what position the author is in, what's the algorithm you'd use to determine who was the first author, the second author, etc? If you issue a select query on a table without providing an "order by" clause, Oracle makes no guarantees about the order in which it retrieves rows.
As an aside, why would you store position number in a varchar2 field? If it's a number, it ought to be stored as a number.
Justin -
PROCEDURE Mktg_Obj_Cmpgn(p_attr_tbl_nm IN attr.attr_tbl_nm%TYPE,p_actn_cd IN chg_log.actn_cd%TYPE) IS
v_tbl_nm varchar2(100);
v_actn_cd varchar2(4);
BEGIN
v_tbl_nm := p_attr_tbl_nm;
v_actn_cd := p_actn_cd;
--dbms_output.put_line(v_tbl_nm);
IF v_actn_cd = 'CRET' THEN
SELECT to_clob(XMLELEMENT("requestmessage",XMLATTRIBUTES(xmlforest(
seq_pblsh_rqst.nextval AS "publish_id")),
XMLAGG(XMLELEMENT("campaign",XMLATTRIBUTES(XMLFOREST(chg.actn_cd AS "ACTION",
pgm.program_idseq AS "parententityvalue",
ent_sbsrb.ENT_ID AS "entid",
pgm.campaign_idseq AS "campaignid",
bus_unt.portfolio_subtype_id AS "campaignsegment",
pgm_typ.pgm_type_nm AS "campaigntype",
LKP.lookup_key_desc AS "campaignclass",
pgm.editor_userid AS "campaignlastmodifiedby",
pgm.edited_dtm AS "campaignlastmodifieddate",
pgm.mkt_initv_proc_tx AS "campaignlink",
ofr.offer_idseq AS "offerlink")))),
XMLAGG(XMLELEMENT("PROCESSCODE", XMLATTRIBUTES(XMLFOREST(action as "link",PROGRAM.program_idseq AS "parententityvalue",
ENT_SBSRB_ATTR.ent_id AS "entid"))))))AS "v_clob" into v_clob1
FROM dual,
chg_log chg,
program pgm,
ent_sbsrb_attr ent_sbsrb,
business_unit bus_unt,
program_type pgm_typ,
offer ofr,
(SELECT lookup_keyword,lookup_key_desc,lookup_type
FROM lookup_key
WHERE lookup_type = 'PRTFL_CMPGN_ID')LKP
WHERE chg.attr_id = ent_sbsrb.attr_id
and chg.parnt_ent_val_tx = to_char(pgm.program_idseq)
and pgm.business_unit_idseq = bus_unt.business_unit_idseq
and pgm.pgm_type_cd = pgm_typ.pgm_type_cd
and ofr.program_idseq = pgm.program_idseq
and pgm.pgm_cls_cd(+) = LKP.lookup_keyword;
END IF;
end Mktg_Obj_Cmpgn;
I have this procedure within a package. v_clob1 is declared in packagebody as a CLOB variable. when i try to compile it i am getting the below given error.can anyone please help me?
(1): PL/SQL: ORA-19208: parameter 1 of function XMLELEMENT must be aliased
(2): PL/SQL: SQL Statement ignoredhi sir,
wanna ask u guyz one query
let say i have table name account(parent) and service(child)
account
id name status
1 john 0
2 ki 1
3 kdf 2
service
id trans_id name status
1 1 et 9999
1 2 eee 2222
2 3 ere 999
2 4 wew 0
i plan to use something like this
delete account from account t1,service t2 where t1id=t2.id and t1.status<>0;
but sql command not correct so plz help me
now i need a query to delete records from service table only but
account.status <> 0 and accound.id=service.id
i dunt want to delete record from account table
so can u help me with this query
thanks
Message was edited by:
mani_um -
Help with simple Query.
I have 2 tables. Table A and Table B
Table A
Client_ID
Client_Name
Table B
Document_ID
Client_ID
Document_Name
I need a SQL query that can return all Client Names and all of the Document Names that each client is missing.
I have seen lots examples all over the web about returning Client Names from Table A that are missing from Table B, but nothing about returning the Document Names from Table B as well.
RobA29>> Clients and Documents <<
Why do you think that those are good table names? Why did you fail to write DDL? This is minimal Netiquette for 30+ years of SQL forums.
Each entity gets table:
CREATE TABLE Clients
(client_id CHAR(10) NOT NULL PRIMARY KEY,
client_name VARCHAR(35) NOT NULL);
CREATE TABLE Documents
(document_id CHAR(10) NOT NULL PRIMARY KEY,
document_name VARCHAR(35) NOT NULL);
Here is one guess (based on nothing you bothered to tell us) at the relationship:
CREATE TABLE Document_Assignments
(client_id CHAR(10) NOT NULL
REFERENCES Clients (client_id),
document_id CHAR(10) NOT NULL
REFERENCES Documents (document_id),
PRIMARY KEY (document_id, client_id));
This is n:m, but put in some UNIQUE constraints and you can get 1:n or m:1 or 1:1; do you know what those terms mean? Why don't you read any book on RDBMS over the holidays before you try to write SQL again? It will help a lot.
--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 -
Help with mysql query plz anyone i am begging!!!
Hi everyone pls forgive me i am new to java. can someone pls tel me where i am going wrong wit this mysql query?
<sql:query var="parish" maxRows="1" dataSource="jdbc/gav">
SELECT ParishName, OwnerOccupierHousehold, OwnerOccupierPercOfOverall, OwnerOccupierCo2Emissions,
SocialRentedHousehold, SocialRentedPercOfOverall, SocialRentedCo2Emissions, PrivateRentedHousehold,
PrivateRentedPercOfOverall, PrivateRentedCo2Emission, TotalHouseholds, TotalPerc, Average,
Total2001, TotalEstimatedTotal2006, EmissionsPerPerson, EmissionPerHousehold, EmissionsPerParish,
EnergyChampionsNeeded, NumberOfPeopleAtWork, NumberOfSchoolAgeChildren
FROM base_data as b
WHERE b.id = ? <sql:param value="${param.id}"/>
<sql:param value="${param.id}"/>
</sql:query>
<c:set var="parish" scope="request" value="${parish.rows[0]}"/>
here is the error i get:
java.sql.SQLException: Parameter index out of range (2 > number of parameters, which is 1).
please any help would be appreciated!!! Thanks in advance guys .here is my code for the form on the index page:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:query var="parish" dataSource="jdbc/gav">
SELECT id, ParishName FROM base_data
</sql:query>
<form action="response.jsp">
Select a Parish: <select name="id">
<c:forEach var="parish" items="${parish.rows}">
<option value="${parish.id}">${parish.ParishName}</option>
</c:forEach>
</select><br><input type="submit" value="submit" name="submit" /></form>
here is the code for the response page:
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<sql:query var="parish" maxRows="1" dataSource="jdbc/gav">
SELECT b.id, b.ParishName, b.OwnerOccupierHousehold, b.OwnerOccupierPercOfOverall, b.OwnerOccupierCo2Emissions,
b.SocialRentedHousehold, b.SocialRentedPercOfOverall, b.SocialRentedCo2Emissions, b.PrivateRentedHousehold,
b.PrivateRentedPercOfOverall, b.PrivateRentedCo2Emission, b.TotalHouseholds, b.TotalPerc, b.Average,
b.Total2001, b.TotalEstimatedTotal2006, b.EmissionsPerPerson, b.EmissionPerHousehold, b.EmissionsPerParish,
b.EnergyChampionsNeeded, b.NumberOfPeopleAtWork, b.NumberOfSchoolAgeChildren
FROM base_data as b
WHERE b.id = ? <sql:param value="${param.id}"/>
</sql:query>
<c:set var="parish" scope="request" value="${parish.rows[0]}"/>
i display the results like this : ${parish.EmissionsPerParish}
the user should be able to select a parish from a form and then sql query created and then i want to show the row results on the response page.
could you tell me where so should be a simple process although not simple enough as it may seem.
thanks for the advice keith -
I am in need of some assistance with rolling up data in a SQL query using Oracle 9i. I think that I have a "working" query, but I cannot get it to complete (ran for 4 hours before killing it). There must be a better way. Anyhow, I have a table "lcec_outage_rollup_tab2", with sample data below:
Device Hierarchy SerialNumber Online Offline
F9997 /B0271/F9997/ 0 0
F1928 /B0271/F9997/F1928/ 0 0
T19928 /B0271/F9997/F1928/T19928/ 3966797 1 0
T19928 /B0271/F9997/F1928/T19928/ 3961826 1 0
T19928 /B0271/F9997/F1928/T19928/ 3936230 0 0
T19928 /B0271/F9997/F1928/T19928/ 3961825 1 0
T25357 /B0271/F9997/F1928/T25357/ 3961824 0 1
T25357 /B0271/F9997/F1928/T25357/ 3833846 1 0
T30525 /B0271/F9997/F1928/T30525/ 9414591 1 0
T32276 /B0271/F9997/F1928/T32276/ 9402547 1 0
T32276 /B0271/F9997/F1928/T32276/ 3966807 1 0
T32276 /B0271/F9997/F1928/T32276/ 3907898 1 0
T33190 /B0271/F9997/F1928/T33190/ 3897790 1 0
T33190 /B0271/F9997/F1928/T33190/ 3966785 0 0
F1929 /B0271/F9997/F1929/ 0 0
T28967 /B0271/F9997/F1929/T28967/ 3963806 1 0
T28967 /B0271/F9997/F1929/T28967/ 3966842 0 1
T28967 /B0271/F9997/F1929/T28967/ 9469217 0 0
I would like a sum of the Offline and Online columns, rolled up by device. So the results would look like:
Hierarchy Online Offline
/B0271/F9997/ 10 2
/B0271/F9997/F1928/ 9 1
/B0271/F9997/F1928/T19928/ 3 0
/B0271/F9997/F1928/T25357/ 1 1
/B0271/F9997/F1928/T30525/ 1 0
/B0271/F9997/F1928/T32276/ 3 0
/B0271/F9997/F1928/T33190/ 1 0
/B0271/F9997/F1929/ 1 1
/B0271/F9997/F1929/T28967/ 1 1
I am working with the following query:
select distinct hierarchy,
(select sum(Online_Status)
from lcec_outage_rollup_tab2 t1
where t1.hierarchy like '%/' || t.device || '/%'
and serialnumber > 0) online_count,
(select sum(Offline_Status)
from lcec_outage_rollup_tab2 t1
where t1.hierarchy like '%/' || t.device || '/%'
and serialnumber > 0) offline_count
from lcec_outage_rollup_tab2 t
There are 217,000 rows in the "lcec_outage_rollup_tab2" table. Any ideas on how to improve this query so that it runs in less than an hour? Fancy indexing? Parallelizing the query? Etc.? Thanks in advance.Hi,
Use GROUP BY and a self_join, like this:
WITH by_hierarchy AS
SELECT hierarchy
, SUM (online_status) AS online
, SUM (offline)status) AS offline
FROM lcec_outage_rollup_tab2
GROUP BY hierarchy
SELECT p.hierarchy
, SUM (c.online) AS online
, SUM (c.offline) AS offline
FROM by_hierarchy p
JOIN by_hierarchy c ON INSTR ( c.hierarchy
, p.hierarchy
) = 1
GROUP BY p.hierarchy
ORDER BY p.hierarchy
;If you'd care to post CREATE TABLE and INSERT statements for the sample data, then I could test this.
INSTR, as shown above, will probably be a little faster than LIKE. -
Hi.. need help with a query
hello guys :)
I need help with this exercise:
Find the most common cooking method in recipes that contain tomatoes.
the 4 tables:
t_recipes
--recipe_no
--recipe_name
t_products
--product_no
-product_name [tomatoes,cucumbers, onions]
t_integration
--product_no
--recipe_no
t_cooking_mode
recipe_no
mode [Frying,baking]
I am realy lost :S
thank youHi,
851072 wrote:
Thank you for your comment :)
But... I didn`t understand the first partSorry, what part is that? You probably understood "Welcome to the forum!" It looks like you understood most of what I said, perhaps before I said it. You seem to be on the right track.
Unlike talking to a co-worker in the next cube, exchanging messages with someone on this forum takes a fair amount of time, so it's worth the time it takes to explain things very clearly, more than you would in conversation. Post all the relevant information, and say exactly what the problem is.
amm i tried to do this:
select t_recipes.recipe_name, count(t_cooking_mode.cooking_mode)
from (t_cooking_mode INNER JOIN t_integration ON t_cooking_mode.recipe_no = t_integration.recipe_no )
INNER JOIN t_products ON t_integration.product_no = t_products.product_no)
WHERE t_products.product_name = 'tomatoes'
GROUP BY t_recipes.recipe_name
help?Please help by posting whatever you know about the problem. For example, if there's a error message, post the complete error message, including the line number.
Help the people who want to help you by formatting your code and making it easy to read and understand. This will help you, too.
For example, here's exactly what you posted, with only the white-space changed to make parallel items, such as parentheses, line up nicely:
select t_recipes.recipe_name
, count(t_cooking_mode.cooking_mode)
from ( t_cooking_mode
INNER JOIN t_integration ON t_cooking_mode.recipe_no = t_integration.recipe_no
INNER JOIN t_products ON t_integration.product_no = t_products.product_no
WHERE t_products.product_name = 'tomatoes'
GROUP BY t_recipes.recipe_nameWhen you format your code like this, it can be very easy to spot errors like unbalanced parentheses. In this case, the ')' right before the WHERE clause has no matching '('. You don't need to use any parentheses at all in the FROM clause. You can simply say:
FROM t_cooking_mode
JOIN t_integration ON t_cooking_mode.recipe_no = t_integration.recipe_no
JOIN t_products ON t_integration.product_no = t_products.product_no
WHERE ...INNER JOIN is the default kind of join, which makes sense, since the majority of all joins are inner joins. I usually say JOIN (instead of INNER JOIN) because it makes the code more compact and easier to read (at least for me), but I won't be maintaining your code, so do what's best for you.
What are you trying to find in this problem? Is it a recipe name or a cooking mode? If it's a cooking mode, the why do you have t_recipes.reciple_name in the SELECT (and GROUP BY) clause? Shouldn't you be using some other column, from some other table?
If I understand the problem correctly, the t_recipes table is not needed in this problem. You won't necessarily use every table in every query.
When you post formatted text on this site, type these 6 characters:
\(small letters only, inside curly brackets) before and after each section of formatted text, to preserve spacing.
Maybe you are looking for
-
I have a 13" Early 2011 Macbook Pro. Last week the hard drive failed (for the second time), and when I took it to the Apple Store I was told it would cost $177 to replace the hard drive and the cables. I intend on going through with this and gettin
-
GarageBand v3 does not show up in Automator
Greetings, I have been trying to create some sort of automation for my Church. We are recording teachings in GBv3. I would like to be able to do the following to make the process as simple as possible through two workflows. First workflow: 1. Open a
-
Problem arose when transfered music from desktop to ipod to new laptop
Please can someone help with my itunes library, this all began when i purchased a new lap top and transfered music files onto my ipod from my old computer(which i have done before and had great succsess). Now the problem began when i synced my ipod t
-
Error code (-9808) when trying to download anything on itunes
Anytime i try to purchase a song on my iTunes a message pops up and it says there has been an unknown error code (-9808) and I'm unable to complete the purchase and download.
-
Hi, I m working on rmi client/server chat application and I would like to make my server replicated (e.g having a group of servers), so when it crashes the connection must jump to another server without losing any data and without the client noticing