如何使用Count()

时间:2017-03-29 08:18:21

标签: sql-server sql-server-2008

[OrderNo]   [OrderStatus]
PO-01       Received
PO-01       Pending
PO-01       Received
PO-02       Pending
PO-02       Pending
PO-03       Received
PO-03       Received

在表a中有两个列OrderNo和OrderStatus 我想得到一个结果。

[OrderNo]   [OrderStatus]
PO-01       Partially Received
PO-02       Pending
PO-03       Received in Full

如果收到所有特定行[OrderNo],则将其状态“全部收到”#39;如果没有表明其状态'部分收到'如果每一行处于待处理状态,则使其状态为“待定”

3 个答案:

答案 0 :(得分:1)

with Orders 
as (
  select distinct OrderNo from TableOrders
)

select OrderNo,

       case when not exists (select * 
                             from TableOrders 
                             where TableOrders.OrderNo = Orders.OrderNo and
                                   OrderStatus = 'Received') 
                 then 'Pending'

             when exists (select *
                          from TableOrders 
                          where TableOrders.OrderNo = Orders.OrderNo and
                                OrderStatus = 'Pending') 
                  then 'Partially Received'

              else 'Received in Full' 
       end as Status              

from Orders

答案 1 :(得分:0)

假设OrderStatus中只有两个状态

declare @sales1 table
(orderNo nvarchar(10), orderStatus nvarchar(20) )
insert into      @sales1

select 'PO-01',       'Received'
union all select 'PO-01',       'Pending'
union all select 'PO-01',       'Received'
union all select 'PO-02',       'Pending'
union all select 'PO-02',       'Pending'
union all select 'PO-03',       'Received'
union all select 'PO-03',       'Received'



 SELECT orderNo
        ,CASE WHEN count(*) = sum(orderStatus)
                AND sum(orderStatus) > 0 THEN 'Pending' WHEN sum(orderStatus) > 0 THEN 'Partially Received' WHEN sum(orderStatus) = 0 THEN 'Received in full' END AS ststus
    FROM (
        SELECT orderNo
            ,CASE WHEN orderStatus = 'Received' THEN 0 ELSE 1 END AS orderStatus
        FROM @sales1
        ) t
    GROUP BY orderNo

答案 2 :(得分:0)

使用JOIN的另一种方式:

false
true