简体   繁体   中英

count row with total

From tbl Department, I am trying to write a stored procedure to display output as shown below where I can find the count from each row based on following conditions:

  1. Total = 100
  2. Total >100 and <=200
  3. Total >200 and <=300
  4. Total >300在此处输入图片说明

    set @select = 'select count(*) as Orders, sum (tbl.Expenses) as Total from tbl group by tbl.Department'

So, how can I dynamically get the output for 4 conditions as shown above based on my @select statement.

I think you just want conditional aggregation:

select sum(case when total = 100 then 1 else 0 end) as condition1,
       sum(case when total > 100 and total <= 200 then 1 else 0 end) as condition2,
       sum(case when total > 200 and total <= 300 then 1 else 0 end) as condition3,
       sum(case when total > 300 then 1 else 0 end) as condition4
from department d;

希望对您有所帮助,选择总计,Sum(Case when total = 100 then NumberOfOrders_Created end )为“Condition1”,Sum(Case when total > 100 and total <= 200 then NumberOfOrders_Created end )为“Condition2”,Sum (当总数 > 200 且总数 <= 300 然后 NumberOfOrders_Created 结束时)作为“条件 3”,总和(当总数 > 200 和总数 <= 300 然后 NumberOfOrders_Created 结束时)作为“条件4”,来自部门,其中 Orders_date 在 '2013-01 之间-01 00:00:00' 和 '2013-12-31 00:00:00' group by 2 order by 1 Desc

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