分组依据并计算相同状态值的总数

时间:2019-06-05 02:39:24

标签: c# sql group-by count linq-to-sql

我有2个表,即订购和存储。这是我需要的表格中的一些字段。

订单表

  OrderId StoreId SystemOrderStatus
     1       1        Received
     2       1        Sent
     3       2        Complete
     4       2        Received

如何获得此输出:

StoreId ReceivedStatusCount SentStatusCount CompleteStatusCount
     1            1                1                0
     2            1                0                1

谢谢。

1 个答案:

答案 0 :(得分:2)

只需使用case when作为打击:

select
    StoreId,
    sum(case when SystemOrderStatus='Received' then 1 else 0 end) as ReceivedStatusCount,
    sum(case when SystemOrderStatus='Sent' then 1 else 0 end) as SentStatusCount,
    sum(case when SystemOrderStatus='Complete' then 1 else 0 end) as CompleteStatusCount
from
    "Order"
group by
    StoreId
order by
    StoreId