SQL 所有发货产品的服务器查询结果

SQL Server query result for all shipping products

我有一个产品 table 如下。

我想获取每个产品的详细信息,其中 product_ship_flag 是 "YES" 相同 order_number 的所有产品。如果任何 product_ship_flag 是 "No" 那么整个 order_number 不应该在输出中。如果所有 product_ship_flag 作为 "No" 那么不应该在输出中。

输出将如下所示:

提前致谢。

已编辑:很少有成员甚至没有尝试去理解问题,有些人无法回答问题,因此投入题。请表现出一些运动精神。

像这样的基本查询不可行吗?

Select * from product where product_ship_flag = 'Yes' group by order_number

试试这个查询:

    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

@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'

查看以下结果:

试试这个。 如果内部查询没有 return 该订单的任何内容,这意味着所有产品 flag_ship 等于 Yes

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')

在这种情况下,左连接可能会很方便。

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