简体   繁体   English

计数行与总数

[英]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:从 tbl 部门,我正在尝试编写一个存储过程来显示输出,如下所示,我可以根据以下条件找到每行的计数:

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

    set @select = 'select count(*) as Orders, sum (tbl.Expenses) as Total from tbl group by tbl.Department' 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.那么,如何根据我的 @select 语句动态获取 4 个条件的输出,如上所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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