SQL queries: find common parts which price has gone up from one type to another - sql

I have a table in the database (big orange one) including parts and prices for two different type. I am looking to find the little orange table as result in summary:
I am looking for common parts in both type R and O Where price has gone up from type O to type R.
This is the script I tried but it is disconnected:
SELECT *FROM Table WHERE type='R'as a
SELECT * FROM Table WHERE type='O'as b
SELECT * FROM a
INNER JOIN b ON a.part = b.part
WHERE a.price < b.price

Please try this and let me know,
SELECT * FROM Table a, Table b
WHERE a.type = 'R'
and b.type = 'O'
and a.part = b.part
and a.price < b.price;

I just found the answer myself:
SELECT * INTO h
FROM table AS t
WHERE t.type='R';
SELECT * INTO b
FROM table AS tab
WHERE tab.type ='O';
SELECT h.type, h.part, h.price, b.price, (b.price - h.price) AS Gap
FROM h
INNER JOIN b ON h.part = b.part;

Related

SQL replase empty row to 0

I am trying to get a list of locks on ORACLE. When there are no locks, an empty string is returned. How to make it output 0 if there are no rows, and output the required result if there are rows?
SELECT (b.seconds_in_wait) as TIME
FROM sys.v_$session b, sys.dba_blockers c, sys.dba_lock a
WHERE c.holding_session = a.session_id AND c.holding_session = b.sid and (username like '%MOBILE%');
I don't even know where to look for the answer)
Left join your sql to a dummy row and handle null with Nvl() function
WITH
dummy AS
( Select 0 "DUMMY" From Dual),
blocked AS
( -- your SQL using Joins
SELECT b.SECONDS_IN_WAIT "A_TIME"
FROM sys.v_$session b
INNER JOIN sys.dba_lock a ON(a.SESSION_ID = b.SID)
INNER JOIN sys.dba_blockers c ON(c.HOLDING_SESSION = b.SID)
WHERE b.username LIKE('%MOBILE%')
)
SELECT Nvl(b.A_TIME, 0) "A_TIME"
FROM dummy
LEFT JOIN blocked b ON(1 = 1)
Use the below by creating a virtual row using DUAL
WITH SUB_QUERY AS(
SELECT (b.seconds_in_wait) as TIME
FROM sys.v_$session b, sys.dba_blockers c, sys.dba_lock a
WHERE c.holding_session = a.session_id AND c.holding_session = b.sid
and(username like '%MOBILE%'))
select * FROM SUB_QUERY
union all
select 0 FROM DUAL
where NOT EXISTS (SELECT 1 FROM SUB_QUERY);
I would simply query the dual table and outer join the wait time query to it, like so:
WITH wait_time AS
(SELECT (b.seconds_in_wait) AS TIME
FROM sys.v_$session b,
sys.dba_blockers c,
sys.dba_lock a
WHERE c.holding_session = a.session_id
AND c.holding_session = b.sid
AND (username LIKE '%MOBILE%'))
SELECT NVL(wt.time, 0)
FROM dual
LEFT OUTER JOIN wait_time wt ON 1=1;
That way, you'll always get at least one row returned, and you're only querying the wait time query once.

Bigquery not picking up a column name to join tables

Why am i getting an error saying that SA2_NAME_2016 is not found when that column is indeed in table c?
select a.Avg__O_Sample_A_5G, a.Avg__O_Sample_A_All_5G, a.Avg__O_Sample_iOS_5G, a.Avg__O_Sample_iOS_All_5G,b.*, c.geomtry
from o-a-c-prd.R_A_K_SCORE_BREAKDOWN.Churn_May as a
left join
(select * from o-a-c-prd.R_A_K_SCORE_BREAKDOWN.A_K_MAY where Month = '2022-05') as b
on
a.SA2 = b.SA2_NAME_2016
JOIN
(select geometry from o-a-c-prd.R_P_Polygons.SA2_GEO_PUB_T ) as c
on
a.SA2 = c.SA2_NAME_2016
The ONLY column available in c is geometry!! So, the error you see makes total sense
Use below instead
select a.Avg__O_Sample_A_5G,
a.Avg__O_Sample_A_All_5G,
a.Avg__O_Sample_iOS_5G,
a.Avg__O_Sample_iOS_All_5G,
b.*,
c.geometry
from o-a-c-prd.R_A_K_SCORE_BREAKDOWN.Churn_May as a
left join
(select * from o-a-c-prd.R_A_K_SCORE_BREAKDOWN.A_K_MAY where Month = '2022-05') as b
on a.SA2 = b.SA2_NAME_2016
JOIN
(select SA2_NAME_2016, geometry from o-a-c-prd.R_P_Polygons.SA2_GEO_PUB_T ) as c
on a.SA2 = c.SA2_NAME_2016

Sql code for distinct fields

I was wondering if anyone can help me with this query.
I have two tables that I join together (DDS2ENVR.QBO AND KCA0001.ORTS)
THE QBO Table has a field labeled NIIN AND RIC. THE KCA0001.ORTS table has a field named SERVICE and OWN_RIC.
I Join the tables by QBO.RIC and ORTS.OWN_RIC. My dilemma is that under the NIIN field multiple rows can be identical but have different values for RIC.
Example:
NIIN RIC
123455 A
122222 B
123456 C
122222 A
I want to query a distinct count for NIINS that separates by the different service where it does not overlap. So example NIIN should only find distinct values only associated with A where the same NIIN is not found in B,C,D etc.
SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1
Please ask questions if this does not make any sense.
Using Not Exists
SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
and NOT EXISTS (Select 1 from DDS2ENVR.QBO C1 where C1.NIIN = C.NIIN and C1.RIC <> C.RIC)
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1
Also if the table DDS2ENVR.QBO doesn't contain duplicates and your dbms supports CTE
With cte as
(Select NIIN from DDS2ENVR.QBO group by NIIN having count(*) = 1)
SELECT D.SERVICE, COUNT(C.NIIN)
FROM DDS2ENVR.QBO C
JOIN KCA0001.ORTS D ON D.OWN_RIC = C.RIC
WHERE C.SITE_ID = ('HEAA')
and C.NIIN in (Select * from cte)
GROUP BY D.SERVICE
HAVING COUNT(DISTINCT C.NIIN) > 1

Existing query optimization

We have 5 tables and we are trying to create a view to get the results.
Below is the view which is working fine.
I need suggestions. Is it a good practice to write this query in this way or it can be optimized in a better way.
SELECT p.Pid, hc.hcid, hc.Accomodation, ghc.ghcid, ghc.ProductFeatures, wp.existing, wp.acute, mc.cardiaccover, mc.cardiaclimitationperiod
FROM TableA p
LEFT JOIN TableB hc
ON p.pid = hc.pid
LEFT JOIN TableC ghc
ON p.pid = ghc.pid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title,
wperiodvalue + '-' + CASE WHEN
wperiodvalue > 1 THEN
unit +
's' ELSE
unit END wperiod
FROM TableD) d
PIVOT ( Max(wperiod)
FOR title IN (acute,
existing
) ) piv1) wp
ON hc.hcid = wp.hcid
LEFT JOIN (SELECT *
FROM (SELECT hcid,
title + col new_col,
value
FROM TableE
CROSS apply ( VALUES (cover,
'Cover'),
(Cast(limitationperiod AS
VARCHAR
(10)),
'LimitationPeriod') ) x (value, col
)) d
PIVOT ( Max(value)
FOR new_col IN (cardiaccover,
cardiaclimitationperiod,
cataracteyelenscover,
cataracteyelenslimitationperiod
) ) piv2) mc
ON hc.hcid = mc.hcid
Any suggestions would be appreciated.
Thanks
My suggestion is to break down the query using temporary table, create stored procedure then dump data in the one new table and with the help of that table you can create view:
Store both PIVOT result in tow seperate temp tables as
SELECT * INTO #pvtInfo FROM ( --first PIVOT query
SELECT * INTO #pvtInfoTwo FROM ( --second PIVOT query
Then your final query will be as :
SELECT p.Pid,
hc.hcid,
hc.Accomodation,
ghc.ghcid,
ghc.ProductFeatures,
wp.existing,
wp.acute,
mc.cardiaccover,
mc.cardiaclimitationperiod
FROM TableA p
LEFT JOIN TableB hc ON p.pid = hc.pid
LEFT JOIN TableC ghc ON p.pid = ghc.pid
LEFT JOIN #pvtInfo wp ON hc.hcid = wp.hcid
LEFT JOIN #pvtInfoTwo mc ON hc.hcid = mc.hcid
First you can try then only go with SP and VIEW.
Hope, It will help.

How can I join on multiple columns within the same table that contain the same type of info?

I am currently joining two tables based on Claim_Number and Customer_Number.
SELECT
A.*,
B.*,
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbp.Compound_Info AS B ON A.Claim_Number = B.Claim_Number AND A.Customer_Number = B.Customer_Number
WHERE A.Filled_YearMonth = '201312' AND A.Compound_Ind = 'Y'
This returns exactly the data I'm looking for. The problem is that I now need to join to another table to get information based on a Product_ID. This would be easy if there was only one Product_ID in the Compound_Info table for each record. However, there are 10. So basically I need to SELECT 10 additional columns for Product_Name based on each of those Product_ID's that are being selected already. How can do that? This is what I was thinking in my head, but is not working right.
SELECT
A.*,
B.*,
PD_Info_1.Product_Name,
PD_Info_2.Product_Name,
....etc {Up to 10 Product Names}
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbo.Compound_Info AS B ON A.Claim_Number = B.Claim_Number AND A.Customer_Number = B.Customer_Number
LEFT JOIN Company.dbo.Product_Info AS PD_Info_1 ON B.Product_ID_1 = PD_Info_1.Product_ID
LEFT JOIN Company.dbo.Product_Info AS PD_Info_2 ON B.Product_ID_2 = PD_Info_2.Product_ID
.... {Up to 10 LEFT JOIN's}
WHERE A.Filled_YearMonth = '201312' AND A.Compound_Ind = 'Y'
This query not only doesn't return the correct results, it also takes forever to run. My actual SQL is a lot longer and I've changed table names, etc but I hope that you can get the idea. If it matters, I will be creating a view based on this query.
Please advise on how to select multiple columns from the same table correctly and efficiently. Thanks!
I found put my extra stuff into CTE and add ROW_NUMBER to insure that I get only 1 row that I care about. it would look something like this. I only did for first 2 product info.
WITH PD_Info
AS ( SELECT Product_ID
,Product_Name
,Effective_Date
,ROW_NUMBER() OVER ( PARTITION BY Product_ID, Product_Name ORDER BY Effective_Date DESC ) AS RowNum
FROM Company.dbo.Product_Info)
SELECT A.*
,B.*
,PD_Info_1.Product_Name
,PD_Info_2.Product_Name
FROM Company.dbo.Company_Master AS A
LEFT JOIN Company.dbo.Compound_Info AS B
ON A.Claim_Number = B.Claim_Number
AND A.Customer_Number = B.Customer_Number
LEFT JOIN PD_Info AS PD_Info_1
ON B.Product_ID_1 = PD_Info_1.Product_ID
AND B.Fill_Date >= PD_Info_1.Effective_Date
AND PD_Info_2.RowNum = 1
LEFT JOIN PD_Info AS PD_Info_2
ON B.Product_ID_2 = PD_Info_2.Product_ID
AND B.Fill_Date >= PD_Info_2.Effective_Date
AND PD_Info_2.RowNum = 1