答案 0 :(得分:1)
这是一个简单的方法:
select avg(case when status = 'Complete' then 100.0 else 0.0 end) as rate
from t;
这使用平均值,这比将完成数求和并除以总数要简单一些。
您实际上也可以将其用join
而不是case
表达式来表达:
select avg(coalesce(v.val, 0.0)) as rate
from t left join
(values ('Complete', 100.0)) v(status, val)
on v.status = t.status
答案 1 :(得分:0)
您可以使用条件聚合:
SELECT 100.0*SUM(IIF(Status='Complete',1, 0)/NULLIF(COUNT(*),0) AS ratio
FROM tab
答案 2 :(得分:0)
根据条件status = 'Completed'
用sum
计算行数:
SELECT
SUM(CASE status WHEN 'Completed' THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS percentage
FROM tablename
答案 3 :(得分:0)
如果我通过您的查询逐步进行简单说明
Select * from
( (( SELECT COUNT(*) FROM TABLE
WHERE STATUS
='Completed` ) /
(SELECT COUNT(Distinct *) FROM TABLE))*100)
答案 4 :(得分:0)
我想知道当同一task_id
具有多个status
时会产生什么含义?
像 111 ?它同时显示“已完成”和“未完成”。
此表中是否可能需要考虑具有日期和时间值的第三列?
此版本的答案可以处理任何“状态”值...
CREATE table my_table
(
task_Id int NOT NULL,
task_status varchar(50) NOT NULL,
);
INSERT INTO my_table VALUES(111, 'Not Completed');
INSERT INTO my_table VALUES(129, 'Completed');
INSERT INTO my_table VALUES(111, 'Completed');
INSERT INTO my_table VALUES(135, 'Not Completed');
INSERT INTO my_table VALUES(136, 'Not Completed');
INSERT INTO my_table VALUES(137, 'Not Completed');
INSERT INTO my_table VALUES(119, 'Completed');
INSERT INTO my_table VALUES(112, 'Not Completed');
INSERT INTO my_table VALUES(118, 'Completed');
INSERT INTO my_table VALUES(126, 'Not Completed');
INSERT INTO my_table VALUES(777, 'In Process');
INSERT INTO my_table VALUES(888, 'In Process');
INSERT INTO my_table VALUES(999, 'Waiting for something');
WITH s1 -- JJAUSSI: count the distinct list of task_id values
AS
(
SELECT COUNT(DISTINCT t.task_id) as task_count_total
FROM my_table t
)
SELECT t.task_status
,CAST(COUNT(DISTINCT t.task_id) AS decimal)/CAST(s1.task_count_total as decimal) as task_status_percent_of_total
,COUNT(DISTINCT t.task_id) as task_status_count
,s1.task_count_total
FROM my_table t
CROSS JOIN s1
GROUP BY t.task_status
,s1.task_count_total
ORDER BY 1;
我在那里使用了一个简单的通用表表达式。
本文在Common Table Expressions中有更多介绍。
这些是结果...
+----+-----------------------+------------------------------+-------------------+------------------+
| | task_status | task_status_percent_of_total | task_status_count | task_count_total |
+----+-----------------------+------------------------------+-------------------+------------------+
| 1 | Completed | 0.3333333333333333333 | 4 | 12 |
| 2 | In Process | 0.1666666666666666666 | 2 | 12 |
| 3 | Not Completed | 0.5000000000000000000 | 6 | 12 |
| 4 | Waiting for something | 0.0833333333333333333 | 1 | 12 |
+----+-----------------------+------------------------------+-------------------+------------------+
我使用this tool创建了ASCII表。希望这可以帮助您入门。