你能在SQL Server中做这样的事情吗?
我想从一个表中进行选择,该表的一列中有一些具有相同product_id的记录,而另一列中有Y或N(库存),并在匹配另一个表中的product_id_set的同时,采用第一个具有相同product_id的Y的记录。
... ,
SELECT
(SELECT TOP 1
(product_name),
CASE
WHEN in_stock = 'Y' THEN product_name
ELSE product_name
END
FROM
Products
WHERE
Products.product_set = Parent_Table.product_set) AS 'Product Name',
...示例数据将为
product_set in_stock product_id product_name
---------------------------------------------------
1 N 12 Orange
1 Y 12 Pear
2 N 12 Apple
2 N 12 Lemon例如,product_set =1的输出将是'Pear‘。
发布于 2017-02-07 10:19:05
因此,根据对以下问题的回答,有两种解决方案。如果没有in_stock值为'Y‘的产品id的记录,应该返回什么吗?其次,如果有多行in_stock为'Y',你关心它选择哪一行吗?
第一个解决方案假设您想要第一行,无论是否有任何"Y“值。
select *
from (select RID = row_number() over (partition by product_set order by in_stock desc) -- i.e. sort Y before N
from Products) a
where a.RID = 1第二个函数只会在至少有一行in_stock的'Y‘的情况下返回值。请注意,如果有多个in_stock项,order by (select null)实际上是在说您并不关心它选择哪个项。如果您确实关心顺序,请将其替换为适当的排序条件。
select *
from (select RID = row_number() over (partition by product_set order by (select null)) -- i.e. sort Y before N
from Products
where in_stock = 'Y') a
where a.RID = 1我不知道您的查询中“父表”的结构是什么,所以我将其简化为假设您仅在Products中就拥有所需的内容。
发布于 2017-02-07 10:17:32
SELECT ISNULL(
(
SELECT TOP 1 product_name
FROM Products
WHERE Products.product_set = Parent_Table.product_set
AND Products.in_stock = 'Y'
), 'Not in the stock') AS 'Product Name'https://stackoverflow.com/questions/42080456
复制相似问题