select statement - oracle

my table looks like this:
If the field name contains cost or quantity for the same lineItemIds, I have to display the result as:
cost is changed from 8*1=8
(fromVal*fromVal) to 9*6=54
(toVal*toVal) for itemID 123.
any help will be appreciated.

SELECT tc.LINE_ITEM_ID ITEM_ID,
tc.FROMVAL COST_FROMVAL,
tq.FROMVAL QTY_FROMVAL,
(tc.FROMVAL*tq.FROMVAL) PROD_FROMVAL,
tc.TOVAL COST_TOVAL,
tq.TOVAL QTY_TOVAL,
(tc.TOVAL*tq.TOVAL) PROD_TOVAL,
FROM
(SELECT LINE_ITEM_ID,
FROMVAL,
TOVAL,
FROM table
WHERE FIELDNAME = 'cost') tc
JOIN (SELECT LINE_ITEM_ID,
FROMVAL,
TOVAL,
FROM table
WHERE FIELDNAME = 'quantity') tq
ON tc.LINE_ITEM_ID = tq.LINE_ITEM_ID

I would look into using product aggregate functions. You'll have to compile them yourself though, Oracle doesn't include them as system functions. http://radino.eu/2010/11/17/product-aggregate-function/
If it's just for this one case where cost or quantity are used, then you could also just use subqueries, or temporary transaction based tables.
I'd provide you with a query example, but unfortunately don't have an Oracle instance accessible presently.

Related

Better solution than left join subqueries?

TablePatient.Patient_ID(PK)
TableProviders.Encounter (joins to PK)
TableProviders.Provider_Type
TableProviders.Provider_ID
TableNames.Full_Name
TableNames.Provider_ID (joins to Table Names)
I want a query that will give, for all the Patient_IDs, the Full_Name of the provider for every Provider ID.
There are about 30 provider_types.
I have made this already using a left join a ton of left joins. It takes a long time to run and I am thinking there is a trick I am missing.
Any help?
Ok, my previous answer didn't match at all what you meant. You want to pivot the table to have on each line one Patient_ID with every Full_name for every provider_type. I assume that each patient has only one provider for one type and not more ; if more, you will have more than one row for each patient, and anyway I don't think it's really possible.
Here is my solution with pivot. The first part is to make it more understandable, so I create a table named TABLE_PATIENT in a subquery.
WITH TABLE_PATIENT AS
(
SELECT TablePatient.Patient_ID,
TableProviders.Provider_Type,
TableNames.Full_Name
FROM TablePatient LEFT JOIN
TableProviders on TablePatient.Patient_ID = TableProviders.Encounter
LEFT JOIN
TableNames on TableNames.Provider_ID = TableProviders.Provider_ID
group by TablePatient.Patient_ID,
TableProviders.Provider_Type,
TableNames.Full_Name
)
SELECT *
FROM TABLE_PATIENT
PIVOT
(
min(Full_name)
for Provider_type in ([type1], [type2],[type3])
) AS PVT
So TABLE_PATIENT just has many rows for each patient, with one provider each row, and the pivot puts everything on a single row. Tell me if something doesn't work.
You need to write every type you want in the [type1],[type2] etc. Just put them inside [], no other character needed as ' or anything else.
If you put only some types, then the query will not show providers of other types.
Tell me if something doesn't work.
If I understand what you mean, you just want to group the answer by Patient Id and then Provider ID. A full name is unique on a provider id right ?
This should be something like
SELECT TablePatient.Patient_ID,
TableProviders.Provider_ID,
TableNames.Full_Name
FROM TablePatient LEFT JOIN
TableProviders on TablePatient.Patient_ID = TableProviders.Encounter
LEFT JOIN
TableNames on TableNames.Provider_ID = TablerProviders.Provider_ID
group by TablePatient.Patient_ID,
TableProviders.Provider_ID,
TableNames.Full_Name
You can either group by TableNames.Full_Name or select First(TableNames.Full_Name) for example if indeed a full name is unique to a provider ID.
Note : I used the SQL server Syntax, there can be différences with Oracle ..

SQL Statement : Update issue

I have these three tables :
RESEARCHER(Re_Id, Re_Name, Re_Address, Re_Phone, Re_HomePhoneNumber,
Re_OfficeNumber, Re_FirstScore, Re_Second_Score)
PUBLICATION(Pub_ID, Pub_Title, Pub_Type, Pub_Publisher, Pub_Year,Pub_Country, Pub_StartingPage, Pub_Number_of_Page, Score1, Score2)
WRITTEN_BY(Re_Id, Pub_ID)
I want to change the authors of the publication “Introduction to Database System” to “Henry Gordon” and “Sarah Parker”.
The problem is in WRITTEN_BY table,I just store the researcher's ID and publication's ID.
My idea is to change the Re_Id in WRITTEN_BY by those names are "Henry Gorgon" , "Sarah Parker" , which are already existed in RESEARCHER table
UPDATE WRITTEN_BY
SET Re_Id = ....( SELECT Re_Id
FROM RESEACHER
WHERE Re_Name = ‘Henry Gordon’ OR Re_Name = ‘Sarah Paker’ )
WHERE Pub_ID IN ( SELECT Pub_ID
FROM PUBLICATION
WHERE Pub_Name = ‘Introduciton to Database system’ );
I have problem in the SET part,so how to write the SQL statement for that requirement?
Here is the sqlfiddle link for my schema : http://sqlfiddle.com/#!9/b9118/1
I'd use something like below query:
DELETE FROM WRITTEN_BY WHERE Pub_ID IN (
SELECT Pub_ID FROM PUBLICATION
WHERE Pub_Title = 'Introduciton to Database system' )
INSERT INTO WRITTEN_BY
SELECT Re_Id,Pub_Id
FROM RESEARCHER CROSS JOIN PUBLICATION
WHERE Re_Name = 'Henry Gordon' OR Re_Name = 'Sarah Paker'
AND Pub_Title like 'Introduciton to Database system'
SELECT * FROM WRITTEN_BY
The idea is to first drop the existing mapping- you should not update it- and the insert a new one.
The reason for delete/insert approach vs update in case of mapping table is justified in favor of delete/insert as most mapping tables contain many-many mapping and usually one-to-many mappings.
Initially we may have a book mapped to say n number of authors where n <>1 then we either add extra rows, or are left with extraneous rows.
See sample fiddle: http://sqlfiddle.com/#!6/a0e72/13
The real deal however is CROSS JOIN. This does not take any ON like other JOINs and is used to produce cartesian product type map.
We are restricting it to get only limited number of rows as per our need by adding suitable WHERE clauses

HIve join without common filed

I have the following tables:
Table1:
user_name Url
Rahul www.cric.info.com
ranbir www.rogby.com
sahil www.google.com
banit www.yahoo.com
Table2:
Keyword category
cric sports
footbal sports
google search
I want to search Table1 by matching the keyword in Table2. I can perform the same using case statement and the query works but it is not the right approach because each time I have to add the case statement when I will add new search keyword.
select user_name from table1
case when url like '%cric%' then sports
else 'undefined'
end as category
from table1;
Thanks find the soluntions for this approach. FIrst we need to do the Join and after that we need to filter the record.
select user_name,url,Keyword,catagory from(select table1.user_name,table1.url ,table2.keyword,table2.catagory from table1 left outer join table2)a where a.url like (concat('%',a.phrase,'%')
Not sure about more current versions, but I've run into a similar problem... the primary issue is that Hive only supports equi-join statements... when you apply logic to either side of the join, it has difficulty translating into a Map Reduce function.
The alternative method, if you have a reliably structured field, is that you can create a matching key from the larger field. For example, if you know that you're looking for your keyword to exist in the second position of a dot-delimited URI, you could do something like:
select
Uri
, split(Uri, "\\.")[1] as matchKey
from
Table1
join Table2 on Table2.keyword = Table1.matchKey
;

Need to select column from subquery into main query

I have a query like below - table names etc. changed for keeping the actual data private
SELECT inv.*,TRUNC(sysdate)
FROM Invoice inv
WHERE (inv.carrier,inv.pro,inv.ndate) IN
(
SELECT carrier,pro,n_dt FROM Order where TRUNC(Order.cr_dt) = TRUNC(sysdate)
)
I am selecting records from Invoice based on Order. i.e. all records from Invoice which are common with order records for today, based on those 3 columns...
Now I want to select Order_Num from Order in my select query as well.. so that I can use the whole thing to insert it into totally seperate table, let's say orderedInvoices.
insert into orderedInvoices(seq_no,..same columns as Inv...,Cr_dt)
(
SELECT **Order.Order_Num**, inv.*,TRUNC(sysdate)
FROM Invoice inv
WHERE (inv.carrier,inv.pro,inv.ndate) IN
(
SELECT carrier,pro,n_dt FROM Order where TRUNC(Order.cr_dt) = TRUNC(sysdate)
)
)
?? - how to do I select that Order_Num in main query for each records of that sub query?
p.s. I understand that trunc(cr_dt) will not use index on cr_dt (if a index is there..) but I couldn't select records unless I omit the time part of it..:(
If the table ORDER1 is unique on CARRIER, PRO and N_DT you can use a JOIN instead of IN to restrict your records, it'll also enable you to select whatever data you want from either table:
select order.order_num, inv.*, trunc(sysdate)
from Invoice inv
join order ord
on inv.carrier = ord.carrier
and inv.pro = ord.pro
and inv.ndate = ord.n_dt
where trunc(order.cr_dt) = trunc(sysdate)
If it's not unique then you have to use DISTINCT to deduplicate your record set.
Though using TRUNC() on CR_DT will not use an index on that column you can use a functional index on this if you do need an index.
create index i_order_trunc_cr_dt on order (trunc(cr_dt));
1. This is a really bad name for a table as it's a keyword, consider using ORDERS instead.

Hint oracle to use indexes on the subquery -- Oracle SQl

I have a query as follows
select *
from
( select id,sum(amt) amt from table_t group by id
) t inner join table_v v on (v.id = t.id)
order by t.amt desc;
table_t has no index and has 738,000 rows and table_v has an index on id and has 158,000 rows.
The query currently fetches the results in 10 seconds.
The explain query plan shows a full table scan.. How can I improve the performance here ?
If I add an index on id for table_t will it help. Because I am using it in a subquery ?
If you have an index on (id,amt) you would minimise the work in the group by/summation process (as it could read the index). If both columns are nullable then you may need to add a "where id is not null" so it will use the index. [That's implied by the later join on id, but may not get inferred by the optimizer.]
Next step would be to use a materialized view for the summation, maybe with an index on (amt,id) (which it could use to avoid the sort). But that is refreshed either at a commit or on request or at scheduled intervals. It doesn't help if you need to do this query as part of a transaction.
Both the index and the materialized view would add work to inserts/updates/deletes on the table but save work in this query.

Resources