How to get the Average of a Row After Getting Count? - sql

I am trying to use an aggregate function to get the average(count( of a row in SQL Server. However, I continue to get this message:
"Cannot perform an aggregate function on an expression containing an aggregate or a subquery."
In the first picture is the table, in the second picture is the table with the counts for each officer_id, I am trying to find the average amount of calls per officer and cannot seem to find the right SQL query to do it.
The query I thought may work is:
SELECT AVG(COUNT(officer_id))
FROM crime_officers
ORDER BY officer_id;
But this is where I get the aggregate error. Does anyone have any recommendations?
UPDATED table with this query
SELECT officer_id, COUNT(crime_id)
FROM crime_officers
GROUP BY officer_id;
Original table: crime_officers

If I understand correctly, this query provides the average number of crimes per officer. A single value, which is equal to the total number of crimes divided between all officers.
SELECT COUNT(*)*1.0/COUNT(distinct officer_id) as 'Average Crimes per Officer'
FROM crime_officers;

Related

Google Sheets Query Function. How can I get only Unique or Distinct Rows?

I am trying to answer a question on a case using the Query function on Google Sheets and am stuck on a particular problem.
I need to get the total number of unique orders per year. I used the formula below and managed to get the total orders per year.
=QUERY(raw_data!$A$1:$U$9995, "select YEAR(C), COUNT(B) group by YEAR(C)", 1)
Where column C is the date and B is the order_id.
The problem is that this returns a total of 9994 orders and includes duplicates of the same order. For example, if a customer purchased 3 different products, they would each be given a line in the database and would count as 3 of the 9994 orders. However, they all have the same order_id.
I need to get the number of unique orders per year. I know this number is 5009 since I did some manual research through Excel, but wanted to find that same total, separated by year, using the Query Function since this is a case to test my SQL Knowledge.
Is this possible? Does the Query Function have a way to get the count for unique order_ids? Thank you very much for your help!
See if this helps
=QUERY(UNIQUE(raw_data!$B$1:$C$9995), "select YEAR(Col2), COUNT(Col1) where Col2 is not null group by YEAR(Col2)", 1)

Rails - group by results of an aggregate function?

Let's say I have a table of Purchases that contain a Customer customer_id and the money they spent on the purchase price. I want to sum the total spent by each customer and then find the frequency of those sums.
I tried something like:
Purchase.
group(:customer_id).
select("SUM(price)").
group("SUM(price)").
count
but received the error ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: aggregate function calls cannot be nested
There's a two step process in which I pluck "SUM(price)" as an array and convert it to a hash with the summed price as the key and the frequency as the value, but I was wondering if there was a one-step query using the Rails syntax.
Do you have other columns on that table ?
Try to group them as well.
Purchase.select("SUM(price),purchase_id").group_by(:purchase_id)
Make sure you take only columns you need and group them.

SQL/CRYSTAL Statement to calculate average datediff()

I have this statement that calculates the difference in time intervals below:
(DateDiff ("s",previous({PROD_TRKG_TRAN.MOD_DATE_TIME}) ,{PROD_TRKG_TRAN.MOD_DATE_TIME}))/60
Now I want to be able to get that average of that datediff(), this is what I believe should work but I'm getting "The remaining text does not appear to be part of the formula". error message:
SELECT ({PROD_TRKG_TRAN.USER_ID}),
({USER_MASTER.USER_NAME}),
Average (diff((DateDiff ("s",previous({PROD_TRKG_TRAN.MOD_DATE_TIME}) ,{PROD_TRKG_TRAN.MOD_DATE_TIME})))/60
You need to group the data so you can get an average for the group. This can be done in your Query but that will remove the details from the results. If you need to see all the detail lines, then leave the datediff formula and return all the results to your report. Then create groups in your report and create a formula that gets the average for the group(s).

How does the aggregation function work with group by

I do not understand the following (returns numbers of comments for articles with the newest ones dates):
SELECT `id_comment`,COUNT(*) AS `number`, MAX(`date`) AS `newest`
FROM `page_comments`
WHERE TO_DAYS( NOW() )-TO_DAYS(`date`) < 90
GROUP BY `id_comment`
ORDER BY `count` DESC,`newest` DESC
I dont understand how come that the MAX function will not return the MAX value of all the page_comments table? That it automatically takes only the max for the given group. When using MAX, I would expect it to return the highest value of the column. I dont understand how it works together with groupig.
You described the behavior yourself quite correctly already: it automatically takes only the max for the given group.
If you group, you do it (per usual) on every column in the result set, that is not aggregated (not using COUNT, SUM, MIN, MAX...)
That way you get distinct values for all non aggregated columns and the aggregated ones will yield a result that only takes the 'current' group into account.
I am just explaining it to the ground.
MAX() - An aggregate function(Works over the group of data).
If ""group by"" clause is NOT specified, the database implicitly groups the data(column specified) considering the entire result set as group.
If specified, it just groups the data(column) in the group logic specified.
It all boils down to analysis order:
FROM
ON
OUTER
WHERE
GROUP BY
CUBE | ROLLUP
HAVING
SELECT
DISTINCT
10 ORDER BY
TOP
so you first have the from clause
Then you cut the relevant rows via where ( so here your sentence : *I don't understand how come that the MAX function will not return the MAX value of all the page_comments* --fails)
then group it
Then you select it.
The max and aggregate functions apply on the data which is already filtered!

Getting average low and high bids in SQL

I am pretty new to SQL and am working with a (what I expected to be easy) little bidding tool.
I am trying to compute average lows and highs from the same column. I have managed to figure out how to use SQL's MIN, MAX, AVG functions, but how would I go about averaging MIN and MAX?
This is the query I am using:
$query = $pdo->prepare("SELECT AVG(bid),MIN(bid),MAX(bid) FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id");
Try the following query to accomplish task
SELECT ((max(bid)+min(bid))/2) as average FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id
Because the predefined avg function takes only one argument that may be column from table or single value. So you have to find the average of the min and max value of bid like above
As You are saying you need to find out the Min of Avg and Max of Avg,
Now what you are doing is group on one column this means Avg(Bid) will return only one value. And the thing that you are doing will make sense only if it is done with two column,
For example you wanna know the min of Averages per day. You need to identify one more column on which base you want to find out max and min of Avg. See in my example i am using Date as second column. the query will go like.
Select Max(MAx_Bid),Min(Min_Bid),Min(Avg_Bid),Max(Avg_Bid) FROM
(SELECT AVG(bid) Avg_Bid,MIN(bid) Mix_Bid,MAX(bid) max_bid FROM bidding WHERE bid_id=:bid_id GROUP BY bid_id,Days_Date(Dummy column))A