我有一个如下的产品表。
我要获取每个产品详细信息的地方,对于具有相同order_number的所有产品,其product_ship_flag为“ YES”。如果product_ship_flag中的任何一个为“ No”,则整个order_number不应出现在输出中。如果所有product_ship_flag均为“否”,则不应出现在输出中。
谢谢。
已编辑 :几乎没有成员甚至不试图理解问题,并且有些成员无法回答问题,因此专门讨论该问题。请表现出一些运动感。
答案 0 :(得分:1)
尝试一下。 如果内部查询未对该订单返回任何内容,则表示所有产品的flag_ship等于“是”
select * from product p
where not exists (
select '1' from product p2
where p2.order_number = p1.order_number
and p2.product_ship_flag = 'No')
答案 1 :(得分:0)
不是这样的基本查询有效吗?
Select * from product where product_ship_flag = 'Yes' group by order_number
答案 2 :(得分:0)
尝试使用此查询:
select * from product where orderno not in (select orderno, count(case when product_ship_flaf='No' then 1 end) from product
group by orderno
having count(case when product_ship_flaf='No' then 1 end)>=1)A
答案 3 :(得分:0)
@irfan_m,可以使用MIN运算符捕获逻辑。例如,当您执行子查询并使用名为flag的列时。您可以根据自己的需求轻松提取订单。 看到下面的模型:
DECLARE @Producttbl TABLE (id int, order_number varchar(20), product_id varchar(20), stock_cnt int, product_ship_flag VARCHAR(3))
INSERT INTO @Producttbl
SELECT 1,'001','SKU1', 1, 'Yes' union all
SELECT 2,'001','SKU2', 2, 'Yes' union all
SELECT 3,'001','SKU3', 1, 'No' union all
SELECT 4,'002','SKU1', 1, 'Yes' union all
SELECT 5,'002','SKU2', 2, 'Yes' union all
SELECT 6,'003','SKU1', 1, 'No' union all
SELECT 7,'003','SKU2', 2, 'No'
SELECT *
FROM
@Producttbl P
JOIN (
SELECT order_number, Flag=MIN(product_ship_flag)
--product_ship_flag is
---"YES" : for all the products of same the order_number
--If any of the product_ship_flag is "No" then the whole order_number should not be in the output.
--If all product_ship_flag as "No" then should not be in the output.
FROM
@Producttbl
GROUP BY
order_number
)S ON
S.order_number=P.order_number
WHERE
S.Flag='Yes'
请参见以下结果:
答案 4 :(得分:0)
在这种情况下,左联接很方便。
DECLARE @ProducttblTEST TABLE (id int, order_number varchar(20), product_id
varchar(20), stock_cnt int, product_ship_flag VARCHAR(3))
INSERT INTO @ProducttblTEST
SELECT 1,'001','SKU1', 1, 'Yes' union all
SELECT 2,'001','SKU2', 2, 'Yes' union all
SELECT 3,'001','SKU3', 1, 'No' union all
SELECT 4,'002','SKU1', 1, 'Yes' union all
SELECT 5,'002','SKU2', 2, 'Yes' union all
SELECT 6,'003','SKU1', 1, 'No' union all
SELECT 7,'003','SKU2', 2, 'No'
select * from @ProducttblTEST a
left join (select * from @ProducttblTEST where product_ship_flag = 'no') b on
a.order_number = b.order_number
where a.product_ship_flag = 'yes' and b.order_number is null