I have a table that contains various performance metric values. I have a query (subQryKPI) built on the fly, that displays these metrics horizontally like so:
| EmployeeID | Sales | Calls | Hours |
--------------------------------------
| 22567 | 4 | 10 | 5 |
| 98321 | 8 | 12 | 6 |
| 24680 | 0 | 0 | 3 |
I have another table that contains the formulas for various KPIs:
| KPI | Formula |
--------------------------------------
| Sales per Call | [Sales] / [Calls] |
| Calls per Hour | [Calls] / [Hours] |
Lastly, I have some VBA code that builds an SQL query to calculate the KPI scores for each person and insert them into a table (tblKPIdata).
Until now the query was built to calculate 1 KPI at a time like this:
INSERT INTO
tblKPIdata
SELECT
EmployeeID,
"Sales per Call" as KPIname,
[Sales]/[Calls] AS KpiScore
FROM
SubQryKPI
This works fine and even works if the Select query includes Div/0 errors (e.g EmployeeID 24680 above); it just appears to filter the errors out which is fine as that suits my needs.
The problem that I am having is that I am trying to update the code to calculate multiple KPIs at the same time. I have tried to do this using a Union query like so:
INSERT INTO
tblKPIdata
SELECT * FROM (
SELECT
EmployeeID,
"Sales per Call" as KPIname,
[Sales]/[Calls] AS KpiScore
FROM
SubQryKPI
UNION ALL
SELECT
EmployeeID,
"Calls per Hour" as KPIname,
[Calls]/[Hours] AS KpiScore
FROM
SubQryKPI)
But it appears that if there is a Div/0 error in the Union query it cannot be inserted into another table. (I cannot use the old trick of IIf(divisor = 0,0... as I never know what the divisor is going to be.
Does anyone know why errors can't be ignored in the same way when they are part of a Union query and if there is any way around this?
You could restructure your query using the splt function to identify the dividend and control the error.
Dim LString as a string
Dim LArray () as a string
LString = "[Calls] / [Hours]"
LArray = Split (LString, "/")
MsgBox LArray (0) // [Calls]
MsgBox LArray (1) // [Hours] <------ apply IIF control
Related
I'm really sorry as this was probably answered before, but I couldn't find something that solved the problem.
In this case, I'm trying to get the result of dividing two sums in the same column.
| Id | month | budget | sales |
| -- | ----- | ------ | ----- |
| 1 | jan | 1000 | 800 |
| 2 | jan | 1000 | 850 |
| 1 | feb | 1200 | 800 |
| 2 | feb | 1100 | 850 |
What i want is to get the % of completition for each id and month (example: get 0,8 or 80% in a fifth column for id 1 in jan)
I have something like
sel
id,
month,
sum (daily_budget) as budget,
sum (daily_sales) as sales,
budget/sales over (partition by 1,2) as efectivenes
from sales
group by 1,2
I know im doing this wrong but I'm kinda new with sql and cant find the way :|
Thanks!
This should do it
CAST(ROUND(SUM(daily_sales) * 100.00 / SUM(daily_budget), 1) AS DECIMAL(5,2)) AS Effectiveness
I'm new at SQL too but maybe I can help. Try this?
sel
id,
month,
sum (daily_budget) as budget,
sum (daily_sales) as sales,
(sum(daily_budget)/sum(daily_sales)) over (partition by id) as efectivenes
from sales
group by id
If you want to ALTER your table so that it contains a fifth column where the result of budget/sales is automatically calculated, all you need to do this add the formula to this auto-generated column. The example I am about to show is based on MySQL.
Open MySQL
Find the table you wish to modify in the Navigator Pane, right-click on it and select "Alter Table"
Add a new row to your table. Make sure you select NN (Not Null) and G (Generated Column) check boxes
In the Default/Expression column, simply enter the expression budget / sales.
Once you run your next query, you should see your column generated and populated with the calculated results. If you simply want the SQL statement to do the same from the console, it will be something like this: ALTER table YOUR_TABLE_NAME add result FLOAT as (budget / sales);
I am trying to create a custom SQL report that will give me a percentage of DispositionCodes that are clicked after a customer service rep ends a call with a customer.
I am currently using a COUNT Alias to count how many times a Disposition code is assigned to a customer call. I would then like to summarize that DispositionCount alias into another column called "Total". Then I would like to see the percentage of times that a disposition code is selected by calculating DispositionCount / Total. Is it possible to SUM an alias to give me a Total count, and then calculate a percentage based off of two Alias columns?
CURRENT QUERY:
SELECT
WrapupData,
ISNULL(WrapupData, 'No Dispos Code Entered') as DispositionCode,
COUNT(CASE WHEN WrapupData IS NULL THEN 0 ELSE 1 END) AS DispositionCount
FROM Termination_Call_Detail tcd
LEFT JOIN dbo.t_Call_Type ct ON ct.CallTypeID = tcd.CallTypeID
GROUP BY
WrapupData
CURRENT OUTPUT
+---------------------+-------------------------+---------------------+
| | | |
+---------------------+-------------------------+---------------------+
| WrapupData | DispositionCode | DispositionCount |
| NULL | No Dispos Code Entered | 8 |
| Appointment Request | Appointment Request | 3 |
+---------------------+-------------------------+---------------------+
DESIRED OUTPUT
+---------------------+-------------------------+------------------+------------------+
| WrapupData | DispositionCode | DispositionCount |Total | Percentage|
| NULL | No Dispos Code Entered | 8 | 11 | 72.72 |
| Appointment Request | Appointment Request | 3 | 11 | 27.27 |
+---------------------+-------------------------+------------------+------------------+
I have tried count(sum(WrapupData))
but WrapupData is varchar and invalid for sum operator.
I have also tried count(sum(DispositionCount))
but DispositionCount comes back as an Invalid column name (I'm assuming because it's an Alias and is only temporary)
Any help or suggestions would be greatly appreciated!
You could use analytic functions here:
SELECT
WrapupData,
ISNULL(WrapupData, 'No Dispos Code Entered') AS DispositionCode,
COUNT(WrapupData) AS DispositionCount,
SUM(COUNT(WrapupData)) OVER () AS Total,
100.0 * COUNT(WrapupData) / SUM(COUNT(WrapupDatalse)) OVER () AS Percentage
FROM Termination_Call_Detail tcd
LEFT JOIN dbo.t_Call_Type ct
ON ct.CallTypeID = tcd.CallTypeID
GROUP BY
WrapupData;
The here is to use SUM() with a window over the entire table, post aggregation, to find the total. We can also find the percentage by normalizing the count using this sum.
I have an MS Access Query which returns the following sample data:
+-----+------+------+
| Ref | ANS1 | ANS2 |
+-----+------+------+
| 123 | A | A |
| 234 | B | B |
| 345 | C | C |
| 456 | D | E |
| 567 | F | G |
| 678 | H | I |
+-----+------+------+
Is it possible to have Access return the overall percentage where ANS1 = ANS2?
So my new query would return:
50
I know how to get a count of the records returned by the original query, but not how to calculate the percentage.
Since you're looking for a percentage of some condition being met across the entire dataset, the task can be reduced to having a function return either 1 (when the condition is validated), or 0 (when the condition is not validated), and then calculating an average across all records.
This could be achieved in a number of ways, one example might be to use a basic iif statement:
select avg(iif(t.ans1=t.ans2,1,0)) from YourTable t
Or, using the knowledge that a boolean value in MS Access is represented using -1 (True) or 0 (False), the expression can be reduced to:
select -avg(t.ans1=t.ans2) from YourTable t
In each of the above, change YourTable to the name of your table.
If you know how to get a count, then apply that same knowledge twice:
SELECT Count([ANS1]) As MatchCount FROM [Data]
WHERE [ANS1] = [ANS2]
divided by the total count
SELECT Count([ANS1]) As AllCount FROM [Data]
To combine both of these in a basic SQL query, one needs a "dummy" query since Access doesn't allow selection of only raw data:
SELECT TOP 1
((SELECT Count([ANS1]) As MatchCount FROM [Data] WHERE [ANS1] = [ANS2])
/
(SELECT Count([ANS1]) As AllCount FROM [Data]))
AS MatchPercent
FROM [Data]
This of course assumes that there is at least one row... so it doesn't divide by zero.
I'm a new junior developer using reporting as a tool to learn the database structure, we have a reporting tool called Cyberquery to produce these reports but i like to mirror what i do in that in SQL Developer so i can learn both.
Unfortunately i have hit a wall with this problem...
I am trying to produce a summary report of product sales over 24 months, broken down by each month like the table below.
| 2014/10 | 2014/11 | 2014/12 | Total
item no | description | qty | value | qty | value | qty | value | qty | value
a item a 4 20 1 5 2 10 7 35
b item b 1 10 2 20 3 30 6 60
Unfortunately i have not been able to format the query to display the results like this. The sql i have been using goes like this:
select * from(
select i.item_no, i.description, sl.line_value, sl.line_qty, sh.invoice_date
from sales_line sl
join sales_header sh on sh.invoice_no = sl.invoice_no
join item i on i.item_no = sl.item_no
where sh.invoice_date >= add_months((last_day(sysdate)+1),-24)
)
So i have tried a few different ways, originally i thought it would be a case of just using group by but after i couldn't get that to work i had a look at using the pivot function and couldn't get that to work either.
Is this possible in SQL?
Kind Regards,
Richard
I'm writing a query in access 2010 and i can't use count(distinct... so I'm running into a bit of trouble with what can be found below:
An example of my table is as follows
Provider | Member ID | Dollars | Status
FacilityA | 1001 | 50 | Pended
FacilityA | 1001 | 100 | Paid
FacilityA | 1002 | 200 | Paid
FacilityB | 1005 | 30 | Pended
FacilityB | 1009 | 90 | Pended
FacilityC | 1001 | 100 | Paid
FacilityC | 1008 | 500 | Paid
I want to return the total # of unique members that have visited each facility, but I also want to get the total dollar amount that is Pended, so for this example the ideal output would be
Provider | # members | Total Pended charges
FacilityA | 2 | 50
FacilityB | 2 | 120
FacilityC | 2 | 0
I tried using some code I found here: Count Distinct in a Group By aggregate function in Access 2007 SQL
and here:
SQL: Count distinct values from one column based on multiple criteria in other columns
Copying the code from the first link provided by gzaxx:
SELECT cd.DiagCode, Count(cd.CustomerID)
FROM (select distinct DiagCode, CustomerID from CustomerTable) as cd
Group By cd.DiagCode;
I can make this work for counting the members:
SELECT cd.Provider_Number, Count(cd.Member_ID)
FROM (select distinct Provider_Number, Member_ID from Claims_Table) as cd
ON claims_table.Provider_Number=cd.Provider_Number
Group By cd.Provider_Number;
However, no matter what I try I can't get a second portion dealing with the dollars to work without causing an error or messing up the calculation on the member count.
SELECT cd.Provider_Number,
-- claims_table.Member_ID, claims_table.Dollars
SUM(IIF ( Claims_Table.Status = 'Pended' , Claims_Table.Dollars , 0 )) as Dollars_Pending,
Count(cd.Member_ID) as Uniq_Members,
Sum(Dollars) as Dollar_Wrong
FROM (select distinct Provider_Number, Member_ID from Claims_Table) as cd inner join #claims_table
ON claims_table.Provider_Number=cd.Provider_Number and claims_table.Member_ID = cd.Member_ID
Group By cd.Provider_Number;
This should work fine based only on the table you described (named Tabelle1):
SELECT Provider, count(MemberID) as [# Members],
NZ(SUM(SWITCH([Status]='Pended', Dollars)),0) as [Total pending charges]
FROM Tabelle1
GROUP BY Provider;
Explanation
I think the first and second column are self-explanatory.
The third column is where most things are done. The SWITCH([Status]='Pended', Dollars) returns the Dollars only if the status is pending. This then gets summed up by SUM. The NZ(..,0) will set the column to 0 if the SUM returns a NULL.
EDIT: This was tested on Access 2016