get a percentage of daily errors - sql

i have 1 table with 2 columns i work with (time,status)
i select a certain day with date_trunc() in the time column and apply condition where status = '404 NOT FOUND'
and divide that with the daily count
to get a percentage of daily errors
status has 2 values 404 NOT FOUND and 200 OK
--------------------------------------------
i wanna get the daily error percentage
i tried :
select case when status = '404 NOT FOUND' then count(time) END / count(time) from log group by date_trunc('day',time);
but got an error i get error column "log.status" must appear in the GROUP BY clause or be used in an aggregate function

You can use something like this:
SELECT days, (ERROR*1.0/TOTAL)*100.0 Percentage FROM
(select date_trunc('day',time) days,
COUNT(case when status = '404 NOT FOUND'
then 1 ELSE NULL END) ERROR,
COUNT(1) TOTAL
from log
group by date_trunc('day',time)) A;

I would do this as:
select date_trunc('day', time) as dte,
avg(case when status <> '200 OK' then 1.0 else 0 end) as daily_rate
from log l
group by dte;
In Postgres, this can further be shortened to:
select date_trunc('day', time) as dte,
avg( (status <> '200 OK')::int ) as daily_rate
from log l
group by dte;

Related

How can I show the percentage of increase or decrease of visits to a page with respect to the previous year in SQL

how are you doing? I need a query in SQL that when entering the current year shows me a percentage of increase or decrease in visits to my page with respect to the previous year, if it can be better by months.
I currently have this query that shows me the number of visits per month on my page, I need to fill the Percentage column with a new query:
SELECT
FORMAT([DateTime], 'MMMM') AS [Month],
COUNT(*) AS [CounterOfVisitors],
'' AS [Percentage]
FROM
[BasicCore.VisitorCounter]
WHERE
YEAR([DateTime]) = 2023
GROUP BY
MONTH([DateTime]), FORMAT([DateTime], 'MMMM')
This is the output:
Thank you so much
You can first scan both 2022 and 2023 data,and then use conditional CASE inside sum function to see year over year comparison.
See the following code as example.
SELECT
FORMAT([DateTime], 'MMMM') AS [Month],
SUM(CASE WHEN YEAR([DateTime])=2023 THEN 1 ELSE 0 END) AS [CounterOfVisitors],
(SUM(CASE WHEN YEAR([DateTime])=2023 THEN 1 ELSE 0 END) * 1.0 / SUM( CASE WHEN YEAR([DateTime])=2022 THEN 1 ELSE 0 END) - 1.0) AS [Percentage]
FROM
[BasicCore.VisitorCounter]
WHERE
YEAR([DateTime]) in (2022,2023)
GROUP BY
MONTH([DateTime]), FORMAT([DateTime], 'MMMM')

Output getting a zero for division

As I am trying to calculate 'PUT', when I run the query I get 0 for that field. Any suggestions on how to fix this?
SELECT
COUNT(x_reasons) as Cancel,
week,
COUNT(case when on_plan = '1' then 1 else null end) *1.0 / count(*) AS PUT
FROM inbound.otpu_plan_raw
WHERE
week IN ('43','44','45','46','47','48', '49','50')
AND x_reasons like '%CLOSED%' and code = 'VC'
Group By 1,2
Can someone tell me why I am getting a zero in Put output?

aggregate function error in case expression

I have this query
SELECT mylearning.Employee_Id,
case
when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0 then '2018 Complete'
when max(case when mylearning.CourseStatusTXT in ('Started', 'Not Started') then 1 else 0 end) = 1 then '2018 Not Complete'
end as Completion_Status
FROM Analytics.myLearning_Completions as mylearning inner join Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID
And I want to add a condition to the first when statement to make it like this
when max(case when not mylearning.CourseStatusTXT = 'Completed' then 1 else 0 end) = 0
and WD.Adjusted_Hire_Date like '2019% '
and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
then '2018 Complete'
but I keep getting this error
Executed as Single statement. Failed [3504 : HY000] Selected non-aggregate values must be part of the associated group.
Elapsed time = 00:00:00.069
How can I fix it?
Like a couple others mentioned, you are trying to mix grouped data with non-aggregated data in your calculation, which is why you're getting the 3504 error. You need to either include the referenced columns in your GROUP BY or include them inside an aggregate function (i.e. MAX).
I'm not 100% sure if this is what you're after, but hopefully it can help you along.
SELECT
mylearning.Employee_Id,
CASE
WHEN
MAX(CASE WHEN NOT mylearning.CourseStatusTXT = 'Completed' THEN 1 ELSE 0 END) = 0 AND
WD.Adjusted_Hire_Date like '2019% ' AND
-- Check if most recently completed course is before Hire (Date + 1 week)
MAX(mylearning.CourseTimeCompletedH) <
CAST(WD.Adjusted_Hire_Date AS DATE FORMAT 'YYYY/MM/DD') + 7
THEN '2018 Complete' -- No incomplete learnings
WHEN MAX(
CASE WHEN mylearning.CourseStatusTXT IN ('Started', 'Not Started') THEN 1 ELSE 0 END
) = 1 THEN '2018 Not Complete' -- Started / Not Started learnings exist
END AS Completion_Status
FROM Analytics.myLearning_Completions as mylearning -- Get learning info
INNER JOIN Analytics.Workday WD on mylearning.Employee_ID = WD.Employee_ID -- Employee info
GROUP BY mylearning.Employee_Id, WD.Adjusted_Hire_Date
This will give you a summary per employee, with a couple assumptions:
Assuming employee_ID value in Analytics.Workday is a unique value (one-to-one join), to use WD.Adjusted_Hire_Date in your comparisons, you just need to include it in the GROUP BY.
Assuming you have multiple courses per employee_Id, in order to use mylearning.CourseTimeCompletedH in your comparisons, you'd need to wrap that in an aggregate like MAX.
The caveat here is that the query will check if the most recently completed course per employee is before the "hire_date" expression, so I'm not sure if that's what you're after.
Give it a try and let me know.
The issue here is that you are mixing detail row by row information in the same query as group or aggregated data. Aggregated data will output a single value for all the rows unless you have a group by clause. If you have a group by clause then it will output a single value for each group. When you are grouping you can also include any values that are in the group by clause since they will be unique for the group.
if you want this data for each employee, then you could group by employee_id. Any other data would need to also be an aggregate like Max(Adjusted_Hire_Date)
Maybe this is what you want?
SELECT
mylearning.employee_id
, case
when CourseStatusTXT = 'Completed' and WD.Adjusted_Hire_Date like '2019%'
and mylearning.CourseTimeCompletedH < cast (WD.Adjusted_Hire_Date as date format 'YYYY/MM/DD') +7
then '2018 Complete'
else '2018 Not Complete'
end CompletionStatus
FROM myLearning_Completions mylearning, Workday WD
WHERE mylearning.employee_id = WD.employee_id

How to display marks in Percentage in SQL?

As an example, I have this dataƩ
Total submission 170
Passed Submission 32
Failed Submission 137
Skipped Submission 1
I need to be able to show:
Pass percentage
Fail Percentage
Skip percentage
Can someone help achieve this in SQL?
since I dont know what the table looks like here is an example on how it could look
select
round(pass/total,2)*100 as passPercentage
, round(fail/total,2)*100 as failPercentage
, round(skip/total,2)*100 as skipPercentage
from table
Its Worked For Me - Answer is :
convert(float,Secondset.PassedSubmission)*100/convert(float,FirstSet.TotalSubmission) as PassPercentage,
(convert(float,FirstSet.TotalSubmission)-(Convert(float,Secondset.PassedSubmission)+Convert(float,thirdset.SkippedSubmission)))*100/convert(float,FirstSet.TotalSubmission)) as FailPercentage,
convert(float,thirdset.SkippedSubmission)*100/convert(float,FirstSet.TotalSubmission) as SkipPercentage
It depends on how your data is structured and how you want to return your results. If you have a table with one row per submission and a status field, you can do either of these:
SELECT status, (COUNT(*) * 1.00) / (SELECT COUNT(*) FROM submission) AS status_pct
FROM submission
GROUP BY status
;
SELECT
(SUM(CASE WHEN status = 'passed' THEN 1 ELSE 0 END) * 1.00) / COUNT(*) AS pass_pct,
(SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) * 1.00) / COUNT(*) AS fail_pct,
(SUM(CASE WHEN status = 'skipped' THEN 1 ELSE 0 END) * 1.00) / COUNT(*) AS skip_pct
FROM submission
;
SQL Fiddle

Using SUM SEC_TO_TIME in MariaDB

Reference from How to sum time using mysql
I want to SUM Field LogsFormatted.Late Every month with query :
SELECT
SUM(CASE
WHEN MONTH (LogsFormatted.DateIn) = 1
THEN SEC_TO_TIME( SUM( TIME_TO_SEC(LogsFormatted.Late)))
ELSE 0 END
) AS '1'
FROM
HrAttLogsFormatted AS LogsFormatted
But the result is
1111 - Invalid use of group function
Where is the problem with the query? resulting in an error output.. Thank you in advance
[EDIT-SOLVED] It's Solved with simply apply
Change format SUM at the beginning of the query
SEC_TO_TIME(SUM(
CASE WHEN MONTH(LogsFormatted.DateIn) = 1 THEN
TIME_TO_SEC(LogsFormatted.Late) END)
) AS '1'
You don't need to call the sum() so many times. You can also move the case condition to the WHERE clause:
SELECT SUM(TIME_TO_SEC(lf.Late))
FROM HrAttLogsFormatted lf
WHERE MONTH(lf.DateIn) = 1 ;
If you want conditional aggregation, then do:
SELECT SUM(CASE WHEN MONTH(lf.DateIn) = 1 THEN TIME_TO_SEC(lf.Late) END)
FROM HrAttLogsFormatted lf;