对于以下视图,我需要计算每天的错误百分比。如何将每两行合并为一个,显示每对中总共404个错误的百分比?
DATE | STATUS | TOTAL
2017-01-01 200 OK 250
2017-01-01 404 NOT FOUND 180
2017-01-02 200 OK 700
2017-01-02 404 NOT FOUND 25
我想将此作为:
DATE | ERRORS (percent)
2017-01-01 41.8
2017-01-02 3.4
我尝试了各种括号和计数,但是我尝试的所有内容都会因为语法错误而引发不同的错误,或者只是挂起而不返回任何内容。
我昨天开始学习SQL - 我已经看到类似的问题已经解决了将两行合并为一行,但我似乎找不到一个针对每个两行合并的特殊情况。
谢谢!
答案 0 :(得分:1)
尝试这样的事情:
Select DATE
, SUM (
CASE WHEN STATUS IN ('404 NOT FOUND', 'OTHER ERROR STATUSES' )
THEN 1 ELSE 0 END ) -- NUMERATOR - Counts Any Errors
/
( COUNT(*) * 1.0 ) -- DENOMINATOR - Counts All Rows
AS ERRORS
FROM TABLE
GROUP BY DATE
答案 1 :(得分:1)
您可以制作一个公用表格表达式(CTE)来计算每天的总数,然后将其加入到仅过滤的表格中,而不仅仅是“未找到”
WITH CTE
AS
(
SELECT
DATE,
SUM(TOTAL) as day_total
FROM Table
GROUP BY DATE
)
SELECT
T1.DATE,
(T1.TOTAL/CTE.day_total) AS ERRORS
FROM Table AS T1
LEFT JOIN CTE ON T1.DATE=CTE.DATE
WHERE T1.STATUS='404 NOT FOUND';
答案 2 :(得分:0)
我尝试过类似的事情
SELECT DATE, (SELECT COUNT(*) FROM TABLE WHERE STATUS IN ('404 NOT FOUND',
'OTHER ERROR STATUSES')) * 1.0 / COUNT(*) * 100 AS ERRORS_PERCENT
FROM TABLE
GROUP BY DATE;