计算行总数

时间:2015-06-09 20:43:15

标签: sql sql-server sql-server-2008 stored-procedures

从tbl部门,我正在尝试编写一个存储过程来显示输出,如下所示,我可以根据以下条件从每行中找到计数:

  1. 总计= 100
  2. 总计> 100且< = 200
  3. 总计> 200且< = 300
  4. 总计> 300 enter image description here

    设置@select ='选择计数(*)作为订单,总和(tbl.Expenses)为tbl组中的总计tbl.Department'

  5. 那么,如何根据我的@select语句动态获取上面显示的4个条件的输出。

2 个答案:

答案 0 :(得分:0)

我认为你只想要条件聚合:

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;

答案 1 :(得分:0)

希望它对你有所帮助, 选择总数,  总和(总数= 100时的情况,然后是NumberOfOrders_Created结束)作为“Condition1”,  总和(总数> 100且总数&lt; = 200然后NumberOfOrders_Created结束时的情况)作为“Condition2”,  总和(总计> 200且总计&lt; = 300然后NumberOfOrders_Created结束时的情况)作为“Condition3”,  总和(总数> 200且总数&lt; = 300然后NumberOfOrders_Created结束时的情况)作为“Condition4”, 来自部门 哪里 Orders_date介于'2013-01-01 00:00:00'和'2013-12-31 00:00:00'之间 分组2 按1描述排序

相关问题