简体   繁体   中英

Sql Server CASE count / dont count

I am trying to select the counts of orders that have gone through our database.

from the orders, there are 3 parts i want to retrieve

  1. total Order Count
  2. Order Count of saleable orders
  3. Order Count of orders that contain just free samples

If an order only contains free samples, the gross value for that order will naturally be 0 , if it is a normal order, the gross will naturally be >0

The gross field is in decimal format.

this is what i am trying to do at the moment.

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

how can i make the COUNT() function only increase by 1 if the order has a positive gross value?

I am doing this in SQLServer

My result is showing that TotalOrders is 1 but OrderCount and Samples are displaying as 0

thanks.

Is this what you want?

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

You may want > 0.00 , but then TotalOrders would be the same as Samples .

强制转换(COUNT(大约> 0.00时为CAS = THEN 1,否则为NULL END)作为样本

your suggested formula should work

with test as (select 1 as gross union all select  -1 as gross union all select  2)
SELECT COUNT(CASE WHEN gross > 0.00 THEN gross ELSE null END) as 'Samples' from test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM