首页 > 解决方案 > Sql Server CASE 计数/不计数

问题描述

我正在尝试选择已通过我们数据库的订单数量。

从订单中,我要检索 3 个部分

  1. 总订单数
  2. 可销售订单的订单数量
  3. 仅包含免费样品的订单数量

如果订单仅包含免费样品,则该订单的总价值自然为0,如果是正常订单,则总价值自然为>0

总字段为十进制格式。

这就是我目前正在尝试做的事情。

COUNT(gross) as 'TotalOrders',
COUNT(case when gross = 0.00 THEN null else gross end) as 'OrderCount', 
COUNT(case when gross > 0.00 THEN gross else null end) as 'Samples',

如果订单具有正值,我如何使COUNT()函数仅增加 1 gross

我正在这样做SQLServer

我的结果显示TotalOrdersis 1 but OrderCount并且Samples正在显示为0

谢谢。

标签: sqlsql-server

解决方案


这是你想要的吗?

sum(case when gross >= 0.00 then 1 else 0 end) as TotalOrders,
sum(case when gross = 0.00 then 1 else 0 end) as OrderCount, 
sum(case when gross > 0.00 then 1 else 0 end) as Samples

你可能会想要> 0.00,但那TotalOrders会是一样的Samples


推荐阅读