I’m trying to use a correlated subquery in my sql code and I can't wrap my head around what I'm doing wrong. A brief description about the code and what I'm trying to do:
The code consists of a big query (ALIASED AS A) which result set looks like a list of customer IDs, offer IDs and response status name ("SOLD","SELLING","IRRELEVANT","NO ANSWER" etc.) of each customer to each offer. The customers IDs and the responses in the result set are non-unique, since more than one offer can be made to each customer, and a customer can have different response for different offers.
The goal is to generate a list of distinct customer IDs and to mark each ID with 0 or 1 flag :
if the ID has AT LEAST ONE offer with status name is "SOLD" or "SELLING" the flag should be 1 otherwise 0. Since each customer has an array of different responses, what I'm trying to do is to check if "SOLD" or "SELLING" appears in this array for each customer ID, using correlated subquery in the case statement and aliasing the big underlying query named A with A1 this time:
select distinct
A.customer_ID,
case when 'SOLD' in (select distinct A1.response from A as A1
where A.customer_ID = A1.customer_ID) OR
'SELLING' in (select distinct A1.response from A as A1
where A.customer_ID = A1.customer_ID)
then 1 else 0 end as FLAG
FROM
(select …) A
What I get is a mistake alert saying there is no such object as A or A1.
Thanks in advance for the help!
You can use exists with cte :
with cte as (
<query here>
)
select c.*,
(case when exists (select 1
from cte c1
where c1.customer_ID = c.customer_ID and
c1.response in ('sold', 'selling')
)
then 1 else 0
end) as flag
from cte c;
You can also do aggregation :
select customer_id,
max(case when a.response in ('sold', 'selling') then 1 else 0 end) as flag
from < query here > a;
group by customer_id;
With statement as suggested by Yogesh is a good option. If you have any performance issues with "WITH" statement. you can create a volatile table and use columns from volatile table in your select statement .
create voltaile table as (select response from where response in ('SOLD','SELLING').
SELECT from customer table < and join voltaile table>.
The only disadvantge here is volatile tables cannot be accessed after you disconnect from session.
Related
I have two following queries. How can I modify this into single query? The result should be true if either query returns data, and false otherwise:
select custId from customer where customerId=3425632456 and custPhone='5653663251';
select accountnumber from account where accountId=524526 and accountPhone='5653663251';
Here custPhone=accountPhone
I think that you want exists:
select case
when exists (select custId from customer where customerId=3425632456 and custPhone='5653663251')
then 1
when exists (select accountnumber from account where accountId=524526 and accountPhone='5653663251')
then 1
else 0
end res
from dual
This query always return a single row, with a single column called res. If any of the subqueries returns something, then res has value 1, else 0.
As a performance bonus for using case, the second subquery is not executed if the first succeeds (this is called short-circuit evaluation). If your queries are time consuming, this can be interesting; make sure to put the less expensive query first.
If you actually want to return the values, then that's different. One option is union all:
select custId from customer where customerId=3425632456 and custPhone='5653663251'
union all
select accountnumber from account where accountId=524526 and accountPhone='5653663251'
Note that, unlike the first query, this does not guarantee that only one row will be returned. Depending on your data, this could give any number of row, 0 included. You might need additional casting to align the datatypes.
You could do a FULL OUTER JOIN on the two tables and check for the count using CASE statement:
SELECT
CASE
WHEN COUNT(*) > 0
THEN 'TRUE'
ELSE 'FALSE'
END result,
FROM
customer c
FULL OUTER JOIN
account a
ON c.custPhone = a.accountPhone
WHERE c.customerId=3425632456
AND a.accountId=524526
AND c.custPhone='5653663251;
Try this
select
custId,
accountnumber
from customer c
left join account a
on c.custPhone = a.accountPhone
where customerId = 3425632456
;
Is there a way to use a SQL statement on 1 table in which the result is the clients who do NOT have one specific attribute?
The table exists of multiple columns. One of them is Clientand another one is Product. One client can have several different records with different product-values.
Every client should at least have one specific product (for example X), next to a lot of different other values of product he can have. I would like to use a statement which returns all clients who don't have product X.
There are several ways:
Using NOT EXISTS as following:
SELECT client
FROM yourTable T
WHERE NOT EXISTS
(SELECT 1 FROM yourTable TIN
WHERE TIN.product = 'product X'
AND T.CLIENT = TIN.CLIENT
);
Using NOT IN
SELECT client
FROM yourTable T
WHERE client not in
(SELECT tin.client FROM yourTable TIN
WHERE TIN.product = 'product X'
);
Using group by, as shown in the other answers
select client
from yourTable
group by client
HAVING COUNT(CASE WHEN product = 'product X' THEN 1 END) = 0;
Aggregation is one simple option:
SELECT client
FROM yourTable
GROUP BY client
HAVING COUNT(CASE WHEN product = 'product X' THEN 1 END) = 0;
This works by keeping a count, for each client, of each record which matches product X. Assuming a client never has this product, the count would be zero.
Try it with NOT IN.
SELECT *
FROM table1
WHERE product NOT IN ('X')
SELECT [Clients] FROM [tablename] WHERE Product != 'X'
Use subquery to get all records which have X and then in the main query get all records which are not in this subset:
SELECT DISTINCT table_name.client FROM table_name WHERE table_name.client NOT IN (SELECT DISTINCT table_name.client FROM table_name WHERE table_name.product = 'X')
I have an SQLite3 database with a table upon which I need to filter by several factors. Once such factor is to filter our rows based on the content of other rows within the same table.
From what I've researched, a self JOIN is going to be required, but I am not sure how I would do that to filter the table by several factors.
Here is a sample table of the data:
Name Part # Status Amount
---------------------------------
Item 1 12345 New $100.00
Item 2 12345 New $15.00
Item 3 35864 Old $132.56
Item 4 12345 Old $15.00
What I need to do is find any Items that have the same Part #, one of them has an "Old" Status and the Amount is the same.
So, first we would get all rows with Part # "12345," and then check if any of the rows have an "Old" status with a matching Amount. In this example, we would have Item2 and Item4 as a result.
What now would need to be done is to return the REST of the rows within the table, that have a "New" Status, essentially discarding those two items.
Desired Output:
Name Part # Status Amount
---------------------------------
Item 1 12345 New $100.00
Removed all "Old" status rows and any "New" that had a matching "Part #" and "Amount" with an "Old" status. (I'm sorry, I know that's very confusing, hence my need for help).
I have looked into the following resources to try and figure this out on my own, but there are so many levels that I am getting confused.
Self-join of a subquery
ZenTut
Compare rows and columns of same table
The first two links dealt with comparing columns within the same table. The third one does seem to be a pretty similar question, but does not have a readable answer (for me, anyway).
I do Java development as well and it would be fairly simple to do this there, but I am hoping for a single SQL query (nested), if possible.
The "not exists" statment should do the trick :
select * from table t1
where t1.Status = 'New'
and not exists (select * from table t2
where t2.Status = 'Old'
and t2.Part = t1.Part
and t2.Amount = t1.Amount);
This is a T-SQL answer. Hope it is translatable. If you have a big data set for matches you might change the not in to !Exists.
select *
from table
where Name not in(
select Name
from table t1
join table t2
on t1.PartNumber = t2.PartNumber
AND t1.Status='New'
AND t2.Status='Old'
and t1.Amount=t2.Amount)
and Status = 'New'
could be using an innner join a grouped select for get status old and not only this
select * from
my_table
INNER JOIN (
select
Part_#
, Amount
, count(distinct Status)
, sum(case when Status = 'Old' then 1 else 0 )
from my_table
group part_#, Amount,
having count(distinct Status)>1
and sum(case when Status = 'Old' then 1 else 0 ) > 0
) t on.t.part_# = my_table.part_#
and status = 'new'
and my_table.Amount <> t.Amount
Tried to understand what you want best I could...
SELECT DISTINCT yt.PartNum, yt.Status, yt.Amount
FROM YourTable yt
JOIN YourTable yt2
ON yt2.PartNum = yt.PartNum
AND yt2.Status = 'Old'
AND yt2.Amount != yt.Amount
WHERE yt.Status = 'New'
This gives everything with a new status that has an old status with a different price.
I am looking to order a list of keys based on the number of orders placed from a database containing order requests. Basically, on table, call it orders(o_partkey, o_returnflag) I am trying to get the total number of returns for each order. I have tried many variations of the following snippet with the goal schema returnlist(partkey, numreturns):
select O.o_partkey as partkey,
count(case when O.o_returnflag = 'R' then 1 else 0 end) as numreturns
from orders O
orderby quantity_returned desc;
I am very new to SQLite and am just jumping into the basics. This is an adjustment of a homework question (the actual question is more complex) but I have simplified down the issue I am having.
Consider using a derived table subquery with SUM() as the aggregate function:
SELECT dT.partkey, dT.numreturns
FROM
(SELECT O.o_partkey as partkey,
SUM(CASE WHEN O.o_returnflag = 'R' THEN 1 ELSE 0 END) as numreturns
FROM [ORDER] O
GROUP BY O.o_partkey) AS dT
ORDER BY dT.numreturns DESC;
Be sure to bracket name of table as [ORDER] is an SQLite key word.
Your problem is that COUNT counts rows, so it counts both 0 and 1 values.
You are not interested in any other rows, so you can just filter out the returns with WHERE:
SELECT o_partkey AS partkey,
COUNT(*) AS numreturns
FROM orders
WHERE o_returnflag = 'R'
ORDER BY 2 DESC;
I need to pass from one select value to another one to get the calculation done and join the results but having problem with this "with" clause sub query.
This one calculates balance from supplied number loan_id from the second query
WITH my_select (balance, type) As
(
select sum(amount_o-amount_h) as balance, type
from decret d
where d.idnumber = **loan_id**
and d.DATE_D <= '2013-10-31'
and type in (1,2,3,4,11,12,13,18,20,25)
group by type
having sum(amount_o-amount_h) <> 0
)
select sum(balance) FROM my_select //just returns client balance
And this one selects clients data and I want for every client add the balance also to the result calculated in first query.
SELECT *, /*balance*/ from clients
where **loan_id** in (select LoanNum
from NumsFromEx)
How to join them together? (I have simplified a little bit queries to show it cleaner)
Given the sample queries, the following should work:
WITH cteBalances AS
(
SELECT loan_id, SUM(amount_o-amount_h) AS balance
FROM decret d
WHERE d.DATE_D <= '2013-10-31'
AND type IN (1,2,3,4,11,12,13,18,20,25)
GROUP BY loan_id
)
SELECT c.*, b.balance
FROM clients c
LEFT JOIN cteBalances b ON b.loan_id = c.loan_id
WHERE loan_id IN (SELECT LoanNum
FROM NumsFromEx)