简体   繁体   中英

SQL SELECT IN returning two attributes

I am trying to understand SELECT IN better. Would this be a valid query?

SELECT name 
FROM products
WHERE product_id IN
(SELECT product_id, SUM(unit_price)
FROM sales
GROUP BY product_id
HAVING (SUM(unit_price) > 200));

No, for the same reason this would not be a valid predicate:

WHERE product_id = (1234, 16)

It makes no sense to compare that one scalar is equal to a tuple.

Note that SQL does allow you to compare a tuple to a tuple:

WHERE (product_id, 16) = (1234, 16)

But the number of elements in both tuples must be the same.

And likewise you can compare a tuple to a subquery that returns a tuple:

WHERE (product_id, 16) IN (SELECT product_id, SUM(unit_price) FROM ...

As long as both tuples have the same number of elements.

Select inside In cannot have 2 columns. This will throw an error. But since you are looking for Product Ids you dont need SUM(Unit_Price) anyway, the below query should work just fine:

SELECT name FROM products WHERE product_id IN (SELECT product_id FROM sales GROUP BY product_id HAVING (SUM(unit_price) > 200));

You can use inner join as well if you want to avoid IN part.

You could use Common Tables Expressions (CTE) to achieve that

;WITH CTE(ProductId, UnitPrice)
AS(
SELECT product_id, SUM(unit_price) 
FROM sales 
GROUP BY product_id 
HAVING (SUM(unit_price) > 200))

SELECT [Name], c.UnitPrice
FROM Products p INNER JOIN CTE c on p.Product_Id = c.ProductId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM