Need help with a JOIN query
Hi,
I am looking for the following result:
PROVIDER_ID SPECIALTY BUCKET CODE RATING FEE
1 FP EM 100 9 20
1 FP SP 300 15 0
1 INFUS EM 100 3 20
1 INFUS EM 200 6 15The base tables are provided below in the with clause. What I am trying to do is, where "code" matches show the fee from t1 else show 0.
I tried a few variotions but just can't seem to get it right.
with t1 as
select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
select 1 as provider_id, 200 as code, 15 as fee, 30 as default_multiplier from dual
, t2 as
select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
SELECT t1.provider_id
, t2.specialty
, t2.bucket
, t2.code
, t2.rating
, t1.fee
FROM t1, t2
ORDER BY 1, 2, 3Any help will be appreciated.
Thanks.
Could I possibly add one more twist to this.
The current result:
PROVIDER_ID SPECI BU CODE RATING FEE
1 FP EM 100 9 20
1 FP SP 300 15 0
1 INFUS EM 100 3 20
1 INFUS EM 200 6 75
2 FP EM 100 9 40
2 FP SP 300 15 0
2 INFUS EM 100 3 40
2 INFUS EM 200 6 0
3 FP EM 100 9 0
3 FP SP 300 15 0
3 INFUS EM 100 3 0
3 INFUS EM 200 6 60The current code:
with t1 as
select 1 as provider_id, 100 as code, 20 as fee, 10 as default_multiplier from dual union all
select 1 as provider_id, 200 as code, 75 as fee, 10 as default_multiplier from dual union all
select 1 as provider_id, 500 as code, 75 as fee, 10 as default_multiplier from dual union all
select 2 as provider_id, 100 as code, 40 as fee, 20 as default_multiplier from dual union all
select 3 as provider_id, 200 as code, 60 as fee, 30 as default_multiplier from dual
, t2 as
select 100 as code, 'INFUS' AS specialty, 'EM' AS bucket, 3 as rating from dual union all
select 200 as code, 'INFUS' AS specialty, 'EM' AS bucket, 6 as rating from dual union all
select 100 as code, 'FP' AS specialty, 'EM' AS bucket, 9 as rating from dual union all
select 300 as code, 'FP' AS specialty, 'SP' AS bucket, 15 as rating from dual
, t3 as
SELECT t1.provider_id
, t2.specialty
, t2.bucket
, t2.code
, t2.rating
, CASE t1.code
WHEN t2.code
THEN t1.fee
ELSE 0
END AS fee
, RANK () OVER (PARTITION BY t1.provider_id, t2.specialty, t2.bucket, t2.code ORDER BY CASE t1.code
WHEN t2.code
THEN t1.fee
ELSE 0
END DESC) AS the_rank
FROM t1
, t2
SELECT DISTINCT provider_id
, specialty
, bucket
, code
, rating
, fee
FROM t3
WHERE the_rank = 1
ORDER BY 1
, 2
, 3
, 4I added the code 500 to t1. Howevere, I don't want this code to show up in the result becuase it is does not exist in t2.
I also added code 200 to t1, to see if that shows properly.
I had to do the rank, becuase I need the proper count of rows.
In reality the row counts are:
t1: 20 Million
t2: 10 Thousand.
So, I would like to avoid doing DISTINCT and ANALYTIC functions on this large set, so any better way of achiving the same result, with a better statement.
Thanks.
Similar Messages
-
Need help with self join query
Hello,
I have table A with the following data
oid parent_oid
10 4
4 2
2 2
12 6
6 6
parent_oid is the parent of oid. I'd like a query that shows the final parent of the oid. The result should show the following
oid final parent
10 2
4 2
2 2
12 6
6 6
I'm using Oracle 10g. I'm familiar with self joins, but that alone will not do the job. Thanks!Hi,
arizona9952 wrote:
... I'm familiar with self joins, but that alone will not do the job.You're absolutely right!
A 2-way self join would work for rows have no parent, or rows that are directly connected to their final ancestor (such as oid=4), but not for anything farther away.
A 3-way self-join would work for one more level away from the final row, but no more. That would be enough for the small set of sample data that you posted, but it would not work if you added a new row with parent_id=10.
An N-way self-join would work for up to N+1 levels, but no more.
You need something that can go any number of levels, such as CONNECT BY:
SELECT CONNECT_BY_ROOT oid AS oid
, parent_oid AS final_parent
FROM a
WHERE CONNECT_BY_ISLEAF = 1
CONNECT BY oid = PRIOR parent_oid
AND oid != parent_oid
;Edited by: Frank Kulash on Feb 22, 2010 7:09 PM
Upon sober reflection, I think that a Top-Down query, like the one below, would be more efficient than a Bottom-Up query, like the one above:
SELECT oid
, CONNECT_BY_ROOT parent_oid AS final_parent
FROM a
START WITH parent_oid = oid
CONNECT BY parent_oid = PRIOR oid
AND oid != PRIOR oid
; -
Need help with Update Join Query
Hello, I am trying to update PID of #child table with PID of #parent table if "lastname & firstname are matches in both table" but my update query is giving some error. Please help and correct the update query. I am also trying to remove any
blank space from starting and ending.
drop table #parent,#child
create table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
insert into #parent values ('100','Josheph','Sumali')
insert into #parent values ('400','Karen','Hunsa')
insert into #parent values ('600','Mursan ',' Terry')
create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
insert into #child values ('2','Josheph ','Sumali ')
insert into #child values ('5','Karen','Kunsi')
insert into #child values ('6','Mursan ','Terry ')
Update #child
set PID = p.PID
from #child C Join
#parent p ON c.LTRIM(RTRIM(lastname) = p.LTRIM(RTRIM(lastname)
AND c.LTRIM(RTRIM(firstname) = p.LTRIM(RTRIM(firstname)
/* Requested Output */
PID lastname firstname
100 Josheph Sumali
600 Mursan Terrycreate table #parent (PID varchar(10), lastname varchar(50), firstname varchar(50))
insert into #parent values ('100','Josheph','Sumali')
insert into #parent values ('400','Karen','Hunsa')
insert into #parent values ('600','Mursan ',' Terry')
create table #child (PID varchar(10), lastname varchar(50), firstname varchar(50))
insert into #child values ('2','Josheph ','Sumali ')
insert into #child values ('5','Karen','Kunsi')
insert into #child values ('6','Mursan ','Terry ')
Merge #child as t
Using #parent as p ON (LTRIM(RTRIM(t.lastname)) = LTRIM(RTRIM(p.lastname))
AND LTRIM(RTRIM(t.firstname)) = LTRIM(RTRIM(p.firstname)) )
When Matched Then
Update
set PID = p.PID;
update #child
Set lastname=LTRIM(RTRIM(lastname)), firstname= LTRIM(RTRIM(firstname));
update #parent
Set lastname=LTRIM(RTRIM(lastname)), firstname = LTRIM(RTRIM(firstname));
select * from #child
select * from #parent
drop table #parent,#child -
I need help with a SELECT query - help!
Hello, I need help with a select statement.
I have a table with 2 fields as shown below
Name | Type
John | 1
John | 2
John | 3
Paul | 1
Paul | 2
Paul | 3
Mark | 1
Mark | 2
I need a query that returns everything where the name has type 1 or 2 but not type 3. So in the example above the qery should bring back all the "Mark" records.
Thanks,
IanOr, if the types are sequential from 1 upwards you could simply do:-
SQL> create table t as
2 select 'John' as name, 1 as type from dual union
3 select 'John',2 from dual union
4 select 'John',3 from dual union
5 select 'Paul',1 from dual union
6 select 'Paul',2 from dual union
7 select 'Paul',3 from dual union
8 select 'Paul',4 from dual union
9 select 'Mark',1 from dual union
10 select 'Mark',2 from dual;
Table created.
SQL> select name
2 from t
3 group by name
4 having count(*) <= 2;
NAME
Mark
SQL>Or another alternative if they aren't sequential:
SQL> ed
Wrote file afiedt.buf
1 select name from (
2 select name, max(type) t
3 from t
4 group by name
5 )
6* where t < 3
SQL> /
NAME
Mark
SQL>Message was edited by:
blushadow -
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 -
Help with Inner Join query in SQL
Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
My table structure is :
table_packages
packageID
package
packageDetails
etc
table_destinations
destinationID
destination
destinationDetails
etc
table_packagedestinations
packageID
destinationID
..so nothing that complicated.
So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
This is the PHP from the header, including my INNER JOIN query....
PHP Code:
<?php
$ParampackageID_WADApackages = "-1";
if (isset($_GET['packageID'])) {
$ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
$ParamSessionpackageID_WADApackages = "-1";
if (isset($_SESSION['WADA_Insert_packages'])) {
$ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
$ParampackageID2_WADApackages = "-1";
if (isset($_GET['packageID'])) {
$ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
mysql_select_db($database_connPackages, $connPackages);
$query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
$WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
$row_WADApackages = mysql_fetch_assoc($WADApackages);
$totalRows_WADApackages = mysql_num_rows($WADApackages);
$colname_educationalDestinations = "1";
if (isset($_GET['PackageID'])) {
$colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
mysql_select_db($database_connPackages, $connPackages);
$query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
$educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
$row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
$totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
?>
And where I'm trying to display the destinations themselves, I have :
<table>
<tr>
<td>Destinations :</td>
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_educationalDestinations['destination']; ?></td>
</tr>
<?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
</table>
If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working.
Thanks.First off, you need to get the database tables so that there is a relationship between them.
In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
table_packages
packageID
package
packageDetails
destination
destinationDetails
etc
If there is a one to many relationship, then the following would be true
packages
packageID
package
packageDetails
etc
destinations
destinationID
packageID
destination
destinationDetails
etc
The above assumes that there are many destinations to one package with the relationship coloured orange.
Once you have the above correct you can apply your query as follows
SELECT *
FROM packages
INNER JOIN destinations
ON packages.packageID = destinations.packageID
WHERE packages.packageID = %s
ORDER BY destination ASC
The above query will show all packages with relevant destinations -
Need help with LikeFilter for querying the keyset instead of value
Hi,
I'm looking for help with the LikeFilter.
I need to query the cache to get all entries with key starting with a particular string.
I could see samples using LikeFilter for querying the values in the cache but not the keyset.
Can someone help?
E.g:
Cache Entries:
abc123 - value1
abc234 - value2
bcd123 - value3
I want to get all entries with key starting with 'abc'.
thanks,
rama.NJ, thanks for the quick reply.
I tried something similar (as below) but this code gives me 'java.lang.NoClassDefFoundError: com/tangosol/util/ValueExtractor'.
KeyExtractor extractor = new KeyExtractor("getKey");
Filter filter = new LikeFilter(extractor, id+":%",'-',false);
-rama.
Edited by: 911950 on Feb 2, 2012 1:18 PM -
Need help with the following query
I have the following data
INVOICE_ID PAID_AMT PYMNT_GROSS_AMT DISCOUNT
10151 1375 1375 55
10151DC -44.81 -44.81 0
20017 25 25 7
Ok the data I want to grab the discount field is paid_amt = pymnt_gross_amt and discount <> 0. If however there is another invoice_id out there (same invoice ID except with a DC appended to it like 10151DC) then you want to select the differece between the discount field without the DC and the Invoice ID with the DC the paid_amt field.
So the results would be.
Invoice_ID Discount
10151 10.19
20017 7
Thanks for all your help!Why scan same table twice when it can be achived using single scan :
Hope this helps :
with inv_data as
(select '10151' invoice_id,
1375 paid_amt,
1375 pymnt_gross_amt,
55 discount from dual
union all
select '10151DC' invoice_id,
-44.81 paid_amt,
-44.81 pymnt_gross_amt,
0 discount from dual
union all
select '20017' invoice_id,
25 paid_amt,
25 pymnt_gross_amt,
7 discount from dual)
select replace(invoice_id,'DC') invoice_id,
sum(case when invoice_id like '%DC' then pymnt_gross_amt
else discount end) discount
from inv_data
group by replace(invoice_id,'DC')
INVOICE DISCOUNT
10151 10.19
20017 7
2 rows selected. -
I have the following table structure,
Table - 1_
ID | Information
1 | abcadskasasa
2 | asdasdasdasd
3 | saeqdfdvsfcsc
Table - 2_
ID | PID
1 | 12
1 | 13
2 | 14
1 | 15
1 | 16
2 | 12
Table - 3_
ID | PARID
1 | 12
2 | 14
1 | 15
Now I want to select for each ID in table 1, the count of number of PID from table 2 and count of number of PARID from table 3.
Desired output:_
ID | COUNT_PID | COUNT_PARID
1 | 4 | 2
2 | 2 | 1
3 | 0 | 0
Could anyone please help me out with this. I am trying to make use of outer joins, but as I work mostly on the front end so, not able to come up with a proper solution for the above.
Thanks in advance,
TejasHi, Tejas,
You might have been doing the outer join correctly.
There's another problem here: joining table_1 to two other tables with which it has a one-to-many relationship.
If you were joining table_1 to just one other table, you could say:
SELECT t1.id
, COUNT (t2.pid) AS count_pid
FROM table_1 t1
LEFT OUTER JOIN table_2 t2 ON t1.id = t2.id
GROUP BY t1.id
ORDER BY t1.id;You could have done the exact same thing with table_3 instead of table_2.
But you can't do the same thing with both table_2 and table_3 at the same time: that would be like cross-joining table_2 and table_3. Instead of showing id=1 having count_pid=4 and count_parid=2, you would get cout_pid=8 and count_parid=8 (since 8 = 4 * 2).
You can do a separate GROUP BY on (at least) one of the tables.
This gets the right results. In the main query, there is only one one-to-many relationship.
WITH t3_summary AS
SELECT id
, COUNT (parid) AS count_parid
FROM table_3
GROUP BY id
SELECT t1.id
, COUNT (t2.pid) AS count_pid
, MAX (t3.count_parid) AS count_parid
FROM table_1 t1
LEFT OUTER JOIN table_2 t2 ON t1.id = t2.id
LEFT OUTER JOIN t3_summary t3 ON t1.id = t3.id
GROUP BY t1.id
ORDER BY t1.id; -
Need help with inner join and distinct rows
Hey Guys,
i have
1) BaseEnv Table
2) Link Table
3) BaseData Table
Link table has three columns Id,BaseEnvId,BaseDataId
the BaseEnvID is unique in the table where as BaseDataId can be repeated i.e multile rows of BaseEnv Table can point to same BaseData table row
Now i want to do BaseEnvTable inner join Link Table inner join BaseData Table and select 5 columsn ; Name,SyncName,Version,PPO,DOM from the BaseData table.. the problem is that after i do the inner join I get duplciate records..
i want to eliminate the duplicate records , can any one help me herePlease post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect.
This is minimal polite behavior on SQL forums. Now we have to guess and type, guess and type, etc. because of your bad manners.
CREATE TABLE Base_Env
(base_env_id CHAR(10) NOT NULL PRIMARY KEY,
Think about the name Base_Data; do you have lots of tables without data? Silly, unh?
CREATE TABLE Base_Data
(base_data_id CHAR(10) NOT NULL PRIMARY KEY,
Your Links table is wrong in concept and implementation. The term “link” refers to a pointer chain structure used in network databases and makes no sense in RDBMS. There is no generic, magic, universal “id” in RDBMS! People that do this are called “id-iots”
in SQL slang.
We can model a particular relationship in a table by referencing the keys in other tables. But we need to know if the relationship is 1:1, 1:m, or n:m. This is the membership of the relationship. Your narrative implies this:
CREATE TABLE Links
(base_env_id CHAR(10) NOT NULL UNIQUE
REFERENCES Base_Env (base_env_id),
base_data_id CHAR(10) NOT NULL
REFERENCES Base_Data (base_data_id));
>> The base_env_id is unique in the table where as base_data_id can be repeated I.e multiple rows of Base_Env Table can point [sic] to same Base_Data table row. <<
Again, RDBMS has no pointers! We have referenced an referencing tables. This is a fundamental concept.
That narrative you posted has no ON clauses! And the narrative is also wrong. There is no generic “name”, etc. What tables were used in your non-query? Replace the ?? in this skeleton:
SELECT ??.something_name, ??.sync_name, ??.something_version,
??.ppo, ??.dom
FROM Base_Env AS E, Links AS L, Base_Data AS D
WHERE ?????????;
>> I want to eliminate the duplicate records [sic], can any one help me here?<<
Where is the sample data? Where is the results? Please read a book on RDBMS so you can post correct SQL and try again.
--CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
in Sets / Trees and Hierarchies in SQL -
Need help with conditional join....
Table 1 - Student
ID# Name
1 # A
2 # B
3 # C
4 # D
Table2 - Marks
ID Marks Display
1 # 10 # Y
1 # 20 # Y
1 # 14 # N
2 # 12 # N
2 # 13 # N
3 # 12 # Y
Result...Need query to do this?..
Want to join above two tables and display marks as X when there is no ID in table marks or there is ID but all marked with display as 'N'...if there is one or more
marked with Y then display with marks..
I am using oracle 11i.
ID NAme Marks
1 # A # 10
1 # A # 20
2 # B # X
3 # C # 12
4 # D # XOr, using ANSI join syntax:
with Table1 as (
select 1 id,'A' name from dual union all
select 2,'B' from dual union all
select 3,'C' from dual union all
select 4,'D' from dual
Table2 as (
select 1 id,10 marks,'Y' display from dual union all
select 1,20,'Y' from dual union all
select 1,14,'N' from dual union all
select 2,12,'N' from dual union all
select 2,13,'N' from dual union all
select 3,12,'Y' from dual
-- end of on-the-fly data sample
select t1.id,
name,
nvl(to_char(marks),'X') marks
from Table1 t1
left join
Table2 t2
on (
t2.id = t1.id
and
display = 'Y'
order by id
ID NAME MARKS
1 A 10
1 A 20
2 B X
3 C 12
4 D X
SQL> SY. -
Need help with outer join filter.
Need a little help filtering a resultset and I cant seem to find a proper way to do this.
/*table*/
create table invoice( farinvc_invh_code varchar2(100),
farinvc_item varchar2(100),
farinvc_po varchar2(100)
create table po(
supplier_number varchar2(60),
supplier_invoice_no varchar2(60),
po_number varchar2(60),
run_date varchar2(60),
PO_LINE_NUMBER varchar2(60) );
/*data*/
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO_ITEM) VALUES ('I0554164', '1', 'P0142245');
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO_ITEM) VALUES ('I0554164', '3', 'P0142245');
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554165', '1', 'P0142246');
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554165', '2', 'P0142246');
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529132260', 'P0142245', '21-NOV-12', '1');
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529137831', 'P0142245', '21-NOV-12', '3');
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100121', '529137831', 'P0142245', '21-NOV-12', '2');
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100122', '145678', 'P0142246', '22-NOV-12', '1');
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100122', '145679', 'P0142246', '22-NOV-12', '2');query im executing.
SELECT farinvc_invh_code,
supplier_number,
supplier_invoice_no,
farinvc_item,
farinvc_po ,
po_number,
run_date,
PO_LINE_NUMBER
FROM INVOICE, PO
WHERE PO_NUMBER = FARINVC_PO(+)
AND FARINVC_ITEM(+) = PO_LINE_NUMBER
result
"FARINVC_INVH_CODE" "SUPPLIER_NUMBER" "SUPPLIER_INVOICE_NO" "FARINVC_ITEM" "FARINVC_PO" "PO_NUMBER" "RUN_DATE" "PO_LINE_NUMBER"
"I0554165" "914100122" "145678" "1" "P0142246" "P0142246" "22-NOV-12" "1"
"I0554165" "914100122" "145679" "2" "P0142246" "P0142246" "22-NOV-12" "2"
"I0554164" "914100121" "529132260" "1" "P0142245" "P0142245" "21-NOV-12" "1"
"I0554164" "914100121" "529137831" "3" "P0142245" "P0142245" "21-NOV-12" "3"
"" "914100121" "529137831" "" "" "P0142245" "21-NOV-12" "2" this is a much larger table and I took an excerpt in order to keep things clear and understanding. I would like to filter this result set to only show the lines that have have the po numbers are the same and line are the same but there is an extra item. in other words like such.
"FARINVC_INVH_CODE" "SUPPLIER_NUMBER" "SUPPLIER_INVOICE_NO" "FARINVC_ITEM" "FARINVC_PO" "PO_NUMBER" "RUN_DATE" "PO_LINE_NUMBER"
"I0554164" "914100121" "529132260" "1" "P0142245" "P0142245" "21-NOV-12" "1"
"I0554164" "914100121" "529137831" "3" "P0142245" "P0142245" "21-NOV-12" "3"
"" "914100121" "529137831" "" "" "P0142245" "21-NOV-12" "2"fair enough frank lets add some extra data to the tables.
for example.
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554167', '1', 'P0142447')
INSERT INTO "INVOICE" (FARINVC_INVH_CODE, FARINVC_ITEM, FARINVC_PO) VALUES ('I0554167', '2', 'P0142447')
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV1', 'P0142247', '25-NOV-12', '1')
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV2', 'P0142247', '25-NOV-12', '2')
INSERT INTO "PO" (SUPPLIER_NUMBER, SUPPLIER_INVOICE_NO, PO_NUMBER, RUN_DATE, PO_LINE_NUMBER) VALUES ('914100123', 'INV3', 'P0142247', '25-NOV-12', '3')if we run the query above we get
"FARINVC_INVH_CODE" "SUPPLIER_NUMBER" "SUPPLIER_INVOICE_NO" "FARINVC_ITEM" "FARINVC_PO" "PO_NUMBER" "RUN_DATE" "PO_LINE_NUMBER"
"I0554164" "914100121" "529132260" "1" "P0142245" "P0142245" "21-NOV-12" "1"
"I0554164" "914100121" "529137831" "3" "P0142245" "P0142245" "21-NOV-12" "3"
"" "914100121" "529137831" "" "" "P0142245" "21-NOV-12" "2"
"" "914100123" "INV2" "" "" "P0142247" "25-NOV-12" "2"
"" "914100123" "INV1" "" "" "P0142247" "25-NOV-12" "1"
"" "914100123" "INV3" "" "" "P0142247" "25-NOV-12" "3" where really what im trying to target is pos and lines that have a match in both tables and there is additional items from the po table that do not have have a match from the invoice table. Furthermore i would only like to see the items that are repeating invoice numbers, in other words my result here should still only be, because "SUPPLIER_INVOICE_NO" is repeating and it does find a match for the po in the invoice table but yet there is an item with the same invoice and po in the po table that does not have a match in the invoice table.
"FARINVC_INVH_CODE" "SUPPLIER_NUMBER" "SUPPLIER_INVOICE_NO" "FARINVC_ITEM" "FARINVC_PO" "PO_NUMBER" "RUN_DATE" "PO_LINE_NUMBER"
"I0554164" "914100121" "529132260" "1" "P0142245" "P0142245" "21-NOV-12" "1"
"I0554164" "914100121" "529137831" "3" "P0142245" "P0142245" "21-NOV-12" "3"
"" "914100121" "529137831" "" "" "P0142245" "21-NOV-12" "2" hope that makes sense, and thanks for working with me on this.
Edited by: mlov83 on Dec 12, 2012 5:53 AM -
Need help with multi database query.
Hello,
I am working on a query between multiple databases to be view on a web app. We have multiple web apps and we are integrating some functionality between them all into one page.
The data will be for a delegate someone sets for themselves (they can have more then one also). I need a way to pull the data view it as follows.
User, UserNumber, DelegateName, ForApp, ForApp, ForApp, ForApp, ForApp, ForApp
I have had no problem pulling the delegates themselves and which apps they are a delegate for, but not which person they are the delegate for.
SELECT DISTINCT
dbo.Employee.Position_Num AS Delegate_Position, dbo.Employee.Name AS [Delegate Name],
(CASE WHEN Hierarchy.dbo.Employee.Position_Num = CVI_Delegate.Delegate THEN 1 ELSE 0 END) AS For_CVI,
(CASE WHEN Hierarchy.dbo.Employee.Position_Num = Travel_Delegate.Delegate THEN 1 ELSE 0 END) AS For_Travel,
(CASE WHEN Hierarchy.dbo.Employee.Position_Num = Dept_Deposits_Delegate.Delegate THEN 1 ELSE 0 END) AS For_DeptDeposit,
dbo.OKCorral_Delegate.For_UserRoles AS For_OkCorralUR, dbo.OKCorral_Delegate.For_FiscalApprover AS For_OkCorralFA,
(CASE WHEN Hierarchy.dbo.Employee.Position_Num = Reqs_Delegate.Delegate THEN 1 ELSE 0 END) AS For_Reqs
FROM dbo.Employee LEFT OUTER JOIN
Reqs.dbo.Delegate AS Reqs_Delegate ON dbo.Employee.Position_Num = Reqs_Delegate.Position LEFT OUTER JOIN
DeptDeposits.dbo.Delegate AS Dept_Deposits_Delegate ON dbo.Employee.Position_Num = Dept_Deposits_Delegate.Position LEFT OUTER JOIN
CVI.dbo.Delegate AS CVI_Delegate ON dbo.Employee.Position_Num = CVI_Delegate.Position LEFT OUTER JOIN
dbo.OKCorral_Delegate ON dbo.Employee.Position_Num = dbo.OKCorral_Delegate.Position LEFT OUTER JOIN
Travel.dbo.Delegate AS Travel_Delegate ON dbo.Employee.Position_Num = Travel_Delegate.Position
This query works fine. The problem I run into is I have to use the same Employee table to get the EmployeeName and Number
Which will be used for both the person and the delegate. Any ideas will be a great help. It had been suggested I use a procedure to accomplish this, but I have no idea where to start that at. I also have tried a nested sbu-query but since
a person can have more then one delegate for an app, this through errors. Thanks.
George FieldsOk, here are the tables Travel Application Database/Delegate Table
INSERT INTO [Travel].[dbo].[Delegate]
([Position]
,[Delegate]
,[StartDate]
,[EndDate]
,[CreateDate]
,[EditDate])
VALUES
(<Position, char(6),>
,<Delegate, char(6),>
,<StartDate, datetime,>
,<EndDate, datetime,>
,<CreateDate, datetime,>
,<EditDate, datetime,>)
GO
Requistions Application /Table Delegates
INSERT INTO [Reqs].[dbo].[Delegate]
([Position]
,[Delegate]
,[StartDate]
,[EndDate]
,[CreateDate]
,[EditDate])
VALUES
(<Position, char(6),>
,<Delegate, char(6),>
,<StartDate, datetime,>
,<EndDate, datetime,>
,<CreateDate, datetime,>
,<EditDate, datetime,>)
GO
Heirarchy Database for Purchasing Application / Delegates Table
INSERT INTO [Hierarchy].[dbo].[OKCorral_Delegate]
([Dept_Campus]
,[For_DeptNum]
,[Position]
,[Delegate]
,[StartDate]
,[EndDate]
,[CreateDate]
,[EditDate]
,[For_FiscalApprover]
,[For_UserRoles])
VALUES
(<Dept_Campus, char(2),>
,<For_DeptNum, char(5),>
,<Position, char(6),>
,<Delegate, char(6),>
,<StartDate, datetime,>
,<EndDate, datetime,>
,<CreateDate, datetime,>
,<EditDate, datetime,>
,<For_FiscalApprover, bit,>
,<For_UserRoles, bit,>)
GO
Heirarchy Database / Employee Table
INSERT INTO [Hierarchy].[dbo].[Employee]
([Dept_Num]
,[Position_Num]
,[Email]
,[Name]
,[Campus]
,[CWID]
,[Student]
,[Employee]
,[OPID]
,[Gender]
,[Birth_Date])
VALUES
(<Dept_Num, char(5),>
,<Position_Num, char(6),>
,<Email, varchar(75),>
,<Name, varchar(150),>
,<Campus, char(2),>
,<CWID, varchar(16),>
,<Student, char(1),>
,<Employee, char(1),>
,<OPID, char(4),>
,<Gender, char(1),>
,<Birth_Date, char(8),>)
GO
The other two databases also have a delegate table similar to the ones above. As you can see all information about an employee is linked by their position number in the Employee Table.
The Position Number is used in the Position field and Delegate field of all the Delegate tables.
I am needing to pull an employee (actually all of them) List them and then show delegates for them by which applications the delegate holds permissions too. Which is the purpose of the delegate. So a delegate may only be a delegate for one application
or multiple which is why I am pulling from multiple databases.
George Fields -
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. -
I have three tables, photos, comments and prices. Their
structures (abbreviated) are as follows:
photos
photoID
photoTitle
prices
priceID
priceValue
photoID_fk
comments
commentID
commentText
photoID_fk
What I need to do is be able to display a list of photos with
their correlating prices and comments, like so:
Photo 1
Price 1
Price 2
Comment 1
comment 2
Photo 2
Price 1
Price 2
Photo 3
Price 1
Price 2
Comment 1
Notice that while each photo will always have the same number
of "price" values, some might have comments and some might not.
I will list the code that I have thus far, but let me briefly
explain what is happening. With the setup I currently have, the
photos display in the proper order with their proper price values
and comments (if any). Unfortunately, on the ones WITH comments,
the list of prices duplicates to match the number of comments
returned. So, if Photo 1 has two comments, it will return "Price 1
Price 2 Price 1 Price 2" for the output of the price section.
I have been pulling my hair out over this, and any help that
anyone could provide would be greatly appreciated and will
potentially save my life.Dan--
Thanks, as always, for your response. Your solution solved
the problem!
As to my database needs, the comments are related only to the
photos.
Basically, I have a a table that holds all information about
photos in a gallery. I have another table which holds all the
comments that users make about the photos. Finally, each and every
photo has 8 sizes (all the same) for sale. So, I don't think the
MTM relationship is there.
Initially, I was simply going to put Size1, Size2, etc. in
the photos table. However, my client wants to be able to add and/or
remove sizes in the future. Therefore, I thought it would be easier
if every photo was given "x" number of entries in the prices table,
where "x" is the number of total price categories (currently 8).
I don't want to monopolize more of your time, but if you have
a second, I would be interested in hearing a more developed
explanation of the restructuring that you proposed at the end of
your last response. If you do not have time, I understand of
course.
Thanks a million for your help on this!
Maybe you are looking for
-
App Store Not Loading READ HERE!! DO NOT RESTORE YOUR DEVICE!!
Ok Applecare Senior Advisor Tad just confirmed with me that the problem people are having with the App Store not loading is an apple issue with there servers, ITS NOT YOUR IPAD so don't go restoring it! It's not happening to everyone however but th
-
Hi all expert, currently i have a Debit, Credit and Balance in Customer Statement. How to create an ageging base on these amount? Have anyone tried before? Could you please brief me. Thanks Regards, Danny
-
Transfer problem: slow and error -53
Hi i have a problem with my IPod classic 120Gb. When i upload music ti my IIpod from ITunes, the first 7 songs are uploaded normally, but then the transfer gets very slow, then it freezes and in some cases i get an error -53.
-
Hello, someone can help me with code? How to search in text file any word and count how many it were repeated? For example test.txt: hi hola hey hi bye hoola hiAnd if I want to know how many times are repeated in test.txt word "Hi" program must say "
-
I have iTunes installed on my Windows 7 machine. When waking up my Windows 7 machine I get a message that says that APSDaemon.exe can't start because MSVCR80.dll is missing. I'm directed to reintall the applicaton. Is this iTunes related? If so,