按组分组的SQL总百分比

时间:2016-01-14 09:22:09

标签: sql-server

我有以下显示产品订单的伪表:

+---------+------+--------------+---------------+
| OrderID | Year | PriorityCode | ShippedOnTime |
+---------+------+--------------+---------------+
|       1 | 2014 | A            | Y             |
|       2 | 2014 | B            | Y             |
|       3 | 2014 | A            | N             |
|       4 | 2015 | C            | Y             |
|       5 | 2015 | B            | Y             |
|       6 | 2015 | A            | N             |
|       7 | 2015 | A            | N             |
|       8 | 2015 | B            | N             |
|       9 | 2015 | C            | Y             |
|      10 | 2015 | C            | Y             |
+---------+------+--------------+---------------+

我需要找到一种方法来查询以查找按PriorityCode分组的ShippedOntime的百分比,而不是总行数。例如:

PriorityCode:A - 总计4,1按时发货= 25%

优先级代码:B - 总共3个,2个按时发货= 33.3%

PriorityCode:C - 总共3个,3个按时发货= 100%


+--------------+------------+
| PriorityCode | Percentage |
+--------------+------------+
| A            | 25         |
| B            | 33.3       |
| C            | 100        |
+--------------+------------+

一直在研究使用Over()函数然后对结果进行分组,但似乎无法弄明白。

我也希望能够按年分组,但是小步骤!

2 个答案:

答案 0 :(得分:2)

您可以按功能在组内使用条件语句,例如count或sum,以实现所需的输出:

select PriorityCode, sum(case when ShippedOnTime="Y" then 1 else 0 end)/count(*) * 100 as percentage
from table
group by PriorityCode

答案 1 :(得分:1)

这应该可以解决问题:

SELECT 
  Year,
  PriorityCode, 
  CAST(SUM(CASE WHEN ShippedOnTime = 'Y' 
                THEN 100.0 ELSE 0
                END)
   / COUNT(*) as DECIMAL(4,1)) Percentage
FROM yourtable
GROUP BY
  PriorityCode, Year