category Item Price
A Pen NULL
B Pen 10
A Pencil 10
B Pencil 8
C Pencil 7
A Note Book 40
B Note Book 30
C Note Book 20
A Bottle NULL
B Bottle 80
A Ball 50
B Ball 40
A Bag 1000
B Bag 800
This is My data i want to Show only category A data if A price is null
then show category B price. I was tried but don't know how i show the
Data
select * from tbl1
where category = case when price is null then 'B' else 'A' end
When Run this query it's show only Category A data
category Item Price
A Pencil 10
A Note Book 40
A Ball 50
A Bag 1000
Something like this
SELECT price
FROM table
WHERE
category = CASE
WHEN price is not null THEN 'A'
ELSE 'B'
END
`
Using a left join and coalesce() (you could also use isnull()):
select a.Category, a.Item, coalesce(a.Price,b.Price) as Price
from yourtable a
left join yourtable b
on a.Item = b.Item
and b.category = 'B'
where a.category = 'A'
coalesce() will return the first non null value from the parameters in order from left to right.
rextester demo: http://rextester.com/FZO89906
returns:
+----------+-----------+-------+
| Category | Item | Price |
+----------+-----------+-------+
| A | Pen | 10 |
| A | Pencil | 10 |
| A | Note Book | 40 |
| A | Bottle | 80 |
| A | Ball | 50 |
| A | Bag | 1000 |
+----------+-----------+-------+
Reference:
coalesce()
isnull()
;WITH cte(category,Item,Price)
AS
(
SELECT 'A','Pen' ,NULL UNION ALL
SELECT 'B','Pen' ,10 UNION ALL
SELECT 'A','Pencil' ,10 UNION ALL
SELECT 'B','Pencil' ,8 UNION ALL
SELECT 'C','Pencil' ,7 UNION ALL
SELECT 'A','Note Book' ,40 UNION ALL
SELECT 'B','Note Book' ,30 UNION ALL
SELECT 'C','Note Book' ,20 UNION ALL
SELECT 'A','Bottle' ,NULL UNION ALL
SELECT 'B','Bottle' ,80 UNION ALL
SELECT 'A','Ball' ,50 UNION ALL
SELECT 'B','Ball' ,40 UNION ALL
SELECT 'A','Bag' ,1000 UNION ALL
SELECT 'B','Bag' ,800
)
SELECT category,Item,Price From
(
SELECT *,ROW_NUMBER()Over(Partition by Price order by Price)seq From
(
SELECT o.* FROM cte i
INNER JOIN cte o
ON o.category=i.category
WHERE o.category='A' AND o.Price!=i.Price
)dt
) Final
where Final.seq=1
OutPut
category Item Price
A Pencil 10
A Note Book 40
A Ball 50
A Bag 1000
Output For value'B'
category Item Price
--------------------------------
B Pencil 8
B Pen 10
B Note Book 30
B Ball 40
B Bottle 80
B Bag 800
I understand it as If an item in a category has a null price it should pick up that specific item from another category having a price
--Filter records having prices
with CTETable as
(
Select distinct category, item, price
from tbl1
where price is not null
)
--distinct items
select * from
(select category, item, price, ROW_NUMBER() over (Partition by Item order by
Category) as RowNo from CTETable)
as c
where c.RowNo=1
Related
I just want to get the result which displays the reference which is not tallied in sum of table2. when i run my query below it will give me an wrong sum which it gets doubled even if group by cusid ,refno.
Table 1
RefNo
CusID
TotalAmount
1
1001
50
2
1001
30
3
1002
40
Table 2
RefNo
CusID
Particular
Amount
1
1001
Paper
30
1
1001
Pencil
30
2
1001
Ball
15
2
1001
Rubber
20
3
1002
Laptop
50
select * from Table1 a
INNER JOIN (Select CusID,RefNo, SUM(Amount) as CorrectTotal from Table2 group by
CusID,RefNo,
)b
ON b.CusID= a.CusID AND b.RefNo= a.RefNo
where a.TotalAmount != CorrectTotal
Expected Result
If you do it with FULL JOIN and with GROUP BY, you will also get rows where there is no record in the other table.
SELECT COALESCE(a.RefNo, b.RefNo) AS RefNo
, COALESCE(a.CusID, b.CusID) AS CusID
, a.TotalAmount
, SUM(b.Amount) AS CorrectTotal
FROM table1 a
FULL JOIN table2 b ON a.RefNo = b.RefNo
AND a.CusID = b.CusID
GROUP BY COALESCE(a.RefNo, b.RefNo)
, COALESCE(a.CusID, b.CusID)
, a.TotalAmount
ORDER BY 1, 2
Output
RefNo
CusID
TotalAmount
CorrectTotal
1
1001
50
60
2
1001
30
35
3
1002
40
50
8
888
88
(null)
9
999
(null)
99
See running demo on SQL Fiddle.
The other answer will work, but if you don't want to mess with a GROUP BY on the whole query you can also use an APPLY to do this:
SELECT a.*, c.CorrectAmount
FROM Table1 a
OUTER APPLY (
SELECT SUM(Amount) AS CorrectAmount
FROM Table2 b
WHERE b.CusID = a.CusID AND b.RefNo = a.RefNo
) c
WHERE a.TotalAmount <> c.CorrectAmount
I have a query and I want to look up the values from other table as a reference but not mess up my current query results. I think I have to use a Outer Left Join, but not sure how to incorporate that with my current query.
My current query looks similar to this:
SELECT a.primary_key,
a.phase,
b.project_number,
c.LENGTH,
d.color
FROM TableA a,
TableB b,
TableC c,
TableD d
WHERE c.primary_key = a.PROJECT_ID
AND b.primary_key = a.PROJECT_ID
AND b.primary_key = d.project_ID
AND (c.date IS NULL OR c.number IS NULL)
AND d.color IN ('black','red','blue')
ORDER BY 1
Now, that gives me a table of 50 results. 'TableContacts' has the look up value to my b.project_number. So say my table of 50 results, only 10 of them have b.project_number, I need the lookup values from 'TableContacts' to also show in my results, but I don't want that to affect my results and cut it down to 10, I still need my original 50 results, just with that additional information. Help?
Just add the CONTACTS table to your joins:
SELECT a.primary_key,
a.phase,
b.project_number,
c.LENGTH,
d.color,
ct.lookup_value --<< this is from the CONTACTS table
FROM TableA a
JOIN TableB b ON b.primary_key = a.PROJECT_ID
JOIN TableC c ON c.primary_key = a.PROJECT_ID
JOIN TableD d ON b.primary_key = d.project_ID
LEFT JOIN contacts ct ON ct.some_column = b.project_Number --<< this is the outer join to the CONTACTS table
WHERE (c.date IS NULL OR c.number IS NULL)
AND d.color IN ('black','red','blue')
ORDER BY 1
As you obfuscated your table and column names it's hard to guess how exactly the join condition on the CONTACTS table should look like.
You could use this approach:
Create a table with the results of your current query:
create table t1 as
SELECT a.primary_key,
a.phase,
b.project_number,
c.LENGTH_col,
d.color
FROM a,b,c,d
WHERE c.primary_key = a.PROJECT_ID
AND b.primary_key = a.PROJECT_ID
AND b.primary_key = d.project_ID
AND (c.date_col IS NULL OR c.number_col IS NULL)
AND d.color IN ('black','red','blue')
ORDER BY 1;
Use a union to get the desired results:
select t1.primary_key, t1.phase, t1.project_number, t1.length_col, t1.color, TableContacts.lookup_column
from t1, TableContacts
where t1.project_number = TableContacts.project_number
UNION
select t1.primary_key, t1.phase, t1.project_number, t1.length_col, t1.color, null
from t1 where t1.project_number is null;
Illustration by creating dummy data:
select * from a;
PRIMARY_KEY | PROJECT_ID | PHASE
1 100 Phase-1
2 200 Phase-2
3 300 Phase-3
4 400 Phase-4
5 500 Phase-5
select * from b;
PRIMARY_KEY | PROJECT_NUMBER
100 null
200 2000
300 3000
400 null
500 5000
select * from c;
PRIMARY_KEY | NUMBER_COL | LENGTH_COL | DATE_COL
100 null 99 null
200 null 99 null
300 null 99 null
400 null 99 null
500 null 99 null
select * from d;
PROJECT_ID | COLOR
100 black
200 red
300 blue
400 black
500 yellow
select * from TableContacts;
PROJECT_NUMBER | LOOKUP_COLUMN
1000 l-1000
2000 l-2000
3000 l-3000
4000 l-4000
5000 l-5000
Existing query in question returns this:
SELECT a.primary_key,
a.phase,
b.project_number,
c.LENGTH_col,
d.color
FROM a,b,c,d
WHERE c.primary_key = a.PROJECT_ID
AND b.primary_key = a.PROJECT_ID
AND b.primary_key = d.project_ID
AND (c.date_col IS NULL OR c.number_col IS NULL)
AND d.color IN ('black','red','blue')
ORDER BY 1;
PRIMARY_KEY | PHASE | PROJECT_NUMBER | LENGTH_COL | COLOR
1 Phase-1 null 99 black
2 Phase-2 2000 99 red
3 Phase-3 3000 99 blue
4 Phase-4 null 99 black
The goal is to populate the lookup_column where project_number is not null. Running the union query provided at start of answer:
select t1.primary_key, t1.phase, t1.project_number, t1.length_col, t1.color, TableContacts.lookup_column
from t1, TableContacts
where t1.project_number = TableContacts.project_number
UNION
select t1.primary_key, t1.phase, t1.project_number, t1.length_col, t1.color, null
from t1 where t1.project_number is null;
PRIMARY_KEY | PHASE | PROJECT_NUMBER | LENGTH_COL | COLOR | LOOKUP_COLUMN
1 Phase-1 null 99 black null
2 Phase-2 2000 99 red l-2000
3 Phase-3 3000 99 blue l-3000
4 Phase-4 null 99 black null
So I have 2 tables, team A and team B, with their score. I want the rank of the score of every member of team A within team B using SQL or vertica, as shown below
Team A Table
user score
-------------
asa 100
bre 200
cqw 50
duy 50
Team B Table
user score
------------
gfh 20
ewr 80
kil 70
cvb 90
Output:
Team A Table
user score rank in team B
------------------------------
asa 100 1
bre 200 1
cqw 50 4
duy 50 4
Try this - and this only works in Vertica.
INTERPOLATE PREVIOUS VALUE is an outer-join predicate specific to Vertica that joins two tables on non-equal columns, using the 'last known' value in the outer-joined table to make a match succeed.
WITH
-- input, don't use in query itself
table_a (the_user,score) AS (
SELECT 'asa',100
UNION ALL SELECT 'bre',200
UNION ALL SELECT 'cqw',50
UNION ALL SELECT 'duy',50
)
,
table_b(the_user,score) AS (
SELECT 'gfh',20
UNION ALL SELECT 'ewr',80
UNION ALL SELECT 'kil',70
UNION ALL SELECT 'cvb',90
)
-- end of input - start WITH clause here
,
ranked_b AS (
SELECT
RANK() OVER(ORDER BY score DESC) AS the_rank
, *
FROM table_b
)
SELECT
a.the_user AS a_user
, a.score AS a_score
, b.the_rank AS rank_in_team_b
FROM table_a a
LEFT JOIN ranked_b b
ON a.score INTERPOLATE PREVIOUS VALUE b.score
ORDER BY 1
;
a_user|a_score|rank_in_team_b
asa | 100| 1
bre | 200| 1
cqw | 50| 4
duy | 50| 4
Simple correlated query should do:
select
a.*,
(select count(*) + 1 from table_b b where b.score > a.score) rank_in_b
from table_a a;
All you need to do is count the number of people with more score than current user in the table b and add 1 to it to get the rank.
I have three tables (simplified version - the whole picture is a bit more complex).
TABLE: CUSTOMER TABLE: PURCHASE1 TABLE: PURCHASE2
=============== ======================= =======================
CustomerID CustomerID | ProductID CustomerID | ProductID
--------------- ------------|---------- ------------|----------
1 1 | 51 1 | 81
2 1 | 52 1 | 82
3 2 | 52 1 | 83
I know the table structure isn't the best but that's not what I need help with. The products held in the purchase tables are of different types, if that helps to provide context.
I'm trying to join the tables, using a query like this:
Select
customer.customerid, purchase1.productid as P1,
purchase2.productid as P2
From
customer
Left join
purchase1 on customer.customerid = purchase1.customerid
Left join
purchase2 on customer.customerid = purchase2.customerid
Where
customer.customerid = 1;
This produces the following:
CustomerID | P1 | P2
--------------------
1 | 51 | 81
1 | 51 | 82
1 | 51 | 83
1 | 52 | 81
1 | 52 | 82
1 | 52 | 83
How do I get it to do this instead?
CustomerID | P1 | P2
-----------|------|---
1 | 51 | null
1 | 52 | null
1 | null | 81
1 | null | 82
1 | null | 83
The first table has a row for every combination of P1 and P2. The second table only has a row for each customer-product combination.
Can I do this without using UNION? The reason I ask, is that because the query will become more complex, using columns from other rows that aren't in PURCHASE1 or PURCHASE2.
If I have to use UNION, how can I do it such that I can still select from other tables and have additional columns in my query?
Use Union . See DEMO. In union, you have to have same number of columns in both queries so use NULL to match number of column in both query
Select * from (Select customer.customerid, purchase1.productid as P1, NULL as P2
from customer
INNER join purchase1
on customer.customerid = purchase1.customerid
UNION ALL
Select customer.customerid, NULL as P1, purchase2.productid as P2
from customer
INNER join purchase2
on customer.customerid = purchase2.customerid) tb
where tb.customerid = 1;
I would do it this way:
select customerid, p1, p2
from customer
left join (
select customerid, productid p1, null p2 from purchase1
union all
select customerid, null p1, productid p2 from purchase2
) using (customerid)
where customerid = 1;
SQLFiddle demo
Now you can attach rest of tables without repeated logic.
I would first of all union up all the tables and then join them to the customer table - like so:
with customer as (select 1 customerid, 'bob' name from dual union all
select 2 customerid, 'ted' name from dual union all
select 3 customerid, 'joe' name from dual),
purchase1 as (select 1 customerid, 51 productid from dual union all
select 1 customerid, 52 productid from dual union all
select 2 customerid, 52 productid from dual),
purchase2 as (select 1 customerid, 81 productid from dual union all
select 1 customerid, 82 productid from dual union all
select 1 customerid, 83 productid from dual),
-- end of mimicking your table and data; main query is below:
purchases as (select customerid, productid productid1, null productid2
from purchase1
union all
select customerid, null productid1, productid productid2
from purchase2)
select c.customerid,
c.name,
p.productid1,
p.productid2
from customer c
inner join purchases p on (c.customerid = p.customerid)
order by c.customerid,
p.productid1,
p.productid2;
CUSTOMERID NAME PRODUCTID1 PRODUCTID2
---------- ---- ---------- ----------
1 bob 51
1 bob 52
1 bob 81
1 bob 82
1 bob 83
2 ted 52
It's probably easiest to just change it to a union query like this.
select customer.customerid, purchase1.productid as P1, null as P2
from customer
left join purchase1
on customer.customerid = purchase1.customerid
union all
select customer.customerid, null as P1, purchase2.productid as P2
from customer
left join purchase2
on customer.customerid = purchase2.customerid
where customer.customerid = 1;
This uses Union, but in a slightly different way, within subqueries, which might provide you more flexibility.
select distinct t1.pID,t2.pID
from (select ID,pID from Puchase1
union all
select ID, null from Purchase1) t1
right join (select ID,pID from Purchase2
union all
select ID, null from Purchase2) t2
on t1.ID = t2.ID
where t1.ID = 1
and (t1.pID is not null or t2.pID is not null)
and (t1.pID is null or t2.pID is null)
In Oracle, is it possible to perform a union where the duplicate condition is on a single column rather than the entire row?
I have table Aand B that have 2 columns: item_name, price. I'd like to create a view that for certain item_names, it looks in table A to see if the item_name is present, and if so use the price in A, if not go to B and use the price in B, then union the rest of item_name in B that have not yet been added to the view.
For example,
Table A Table B
---------------- ----------------
item_name price item_name price
---------------- ----------------
shoe 10 shoe 8
socks 2 socks 4
shirt 5 t-shirt 3
gloves 1 glasses 15
pants 7
For shoe and socks I'd like to use table A's prices if available, and if not use table B. So in the end, my view should look like this:
View
-----------------------
item_name price source
-----------------------
shoe 10 A
socks 2 A
t-shirt 3 B
glasses 15 B
pants 7 B
I tried
select * from A a
where item_name in ('shoe', 'socks')
union
select * from B b
where b.item_name not in
(select item_name from A
where item_name in ('shoe', 'socks'))
Which I don't like because the query select * from A where item_name in ('shoe', 'socks') is duplicated. Is there a better/more efficient way of doing this?
I think you are looking for a join:
select coalesce(a.item_name, b.item_name) as item_name,
coalesce(a.price, b.price) as price,
(case when a.price is not null then 'A' else 'B' end) as source
from a full outer join
b
on a.item_name = b.item_name
Since you are using Oracle, I may suggest the following, it would do the trick
select NVL(A.ITEM_NAME,B.ITEM_NAME) AS ITEM_NAME,
NVL(A.PRICE,B.PRICE) AS PRICE
FROM A as a RIGHT JOIN B as b ON A.ITEM_NAME=B.ITEM_NAME
To understand why it works, simply try it without NVL, the resulting right join results
A_item A_price B_item B_price
shoe 10 shoe 8
socks 2 socks 4
(null) (null) glasses 15
(null) (null) t-shirt 3
(null) (null) pants 7
Since you do not want the null values from table A, use NVL
NVL has also equivalent functions in mysql/mssql etc
Try this,
create view viewname as (
select coalesce(a.item_name, b.item_name) as item_name,
coalesce(a.price, b.price) as price,
(case when a.item_name=b.item_name then 'A' else 'B' end) as source
from tablea a right outer join
tableb b
on a.item_name = b.item_name)
made slight change Gordon's ans