Running a cumulative Union in mysql - mysql

I am trying to get a list, a total, and a cumulative total in the same column. So far I have the list and the total for that date range, but moving forward I would like to get a cumulative total. Here is the code i'm using, please note temp_2 and temp_3 yield the same results;
Select School,Principal, NumberOfObs
From temp_2
Union
Select '','TOTAL',Sum(NumberOfObs)
From temp_3;
Any thoughts?

Related

What is difference for below there two sql queries

select
substr(insert_date, 1, 14),
device, count(1)
from
abc.xyztable
where
insert_date >= DATE_SUB(NOW(), INTERVAL 10 DAY)
group by
device, substr(insert_date, 1, 14) ;
and then I am trying to get average of the same rows count which I got above.
SELECT
date, device, AVG(count)
FROM
(SELECT
substr(insert_date, 1, 14) AS date,
device,
COUNT(1) AS count
FROM
abc.xyztable
WHERE
insert_date >= DATE_SUB(NOW(), INTERVAL 10 DAY)
GROUP BY
device, substr(insert_date, 1, 14)) a
GROUP BY
device, date;
AS I found both queries return the same results, I tried for last 10 days data.
My purpose is to get the average rows count for last 10 days which I get from the above 1st query.
I'm not entirely sure what you're asking, the "difference" between the two queries is that the first one is valid but the second does not appear to be, as per HoneyBadger's comment. They also seem to be trying to achieve two different goals.
However, I think what you are trying to do is produce a query based on the data from the first query, which returns the date, device, and an average of the count column. If so, I believe the following query would calculate this:
WITH
dataset AS (
select substr(insert_date,1,14) AS theDate, device, count(*) AS
theCount
from abc.xyztable
where insert_date >=DATE_SUB(NOW(), INTERVAL 10 DAY)
group by device,substr(insert_date,1,14)
)
SELECT theDate, device, (SELECT ROUND(AVG(CAST(theCount
AS FLOAT)), 2) FROM
dataset) AS Average
FROM dataset
GROUP BY theDate, device
I have referenced the accepted answers of this question to calculate the average: How to calculate average of a column and then include it in a select query in oracle?
And this question to tidy up the query: Formatting Clear and readable SQL queries
Without having a sample of your data, or any proper context, I can't see how this would be especially useful, so if it was not what you were looking for, please edit your question and clarify exactly what you need.
EDIT: Based on what extra information you have provided, I've made a tweak to my solution to increase the precision of the average column. It now calculates the average to two decimal places. You have stated that this returns the same result as your original query, but the two queries are not formulating the same thing. If the count column is consistently the same number with little variation, the AVG function will round this, which in turn could produce results which look the same, especially if you only compare a small sample, so I have amended my answer to demonstrate this. Again, we'd all be able to help you much easier if you would provide more information, such as a sample of your data.
If you want an average you need to change the last GROUP BY
to get an average per device
GROUP BY device;
to get an average per date
GROUP BY date;
or remove it completely to get an average for all rows in the sub-query
Update
Below is a full example for getting the average per device
SELECT device, avg(count)
FROM (SELECT substr(insert_date,1,14) as date, device, count(1) as count
FROM abc.xyztable
WHERE insert_date >=DATE_SUB(NOW(), INTERVAL 10 DAY)
GROUP BY device,substr(insert_date,1,14)) a
GROUP BY device;

Dealing with the count function

My Boss want to know how many times each of these shipping number of days occurred. Ordered by number of days DESC.
So far have :
SELECT DateDiff(shippedDate,orderDate) As '#Days', COUNT(*)
FROM datenumtest
I think I need condition, can someone help me out with this?
Calculate the DateDiff across all records first in a data set r, then you can do the grouping on that data set which becomes data set r1 then sort the r1 data set:
select r.NumDays, count(1) as the_count
from (
SELECT DateDiff(shippedDate,orderDate) as 'NumDays'
FROM datenumtest
) r
group by r.NumDays
order by r.NumDays desc;

Trying to multiply columns but can't get the different ones to add when grouping in mySQL

select eventcode, count(eventcode) * price, min(showdate), max(showdate), price
from ticket
group by price;
Please look at the image for better context but I am trying to return the total cost for each eventcode in my query. But when I group by eventcode it doesn't include the different prices that can occur and only returns the first one that it finds. Grouping by price shows the different values that I would like to return together. For example for eventcode 801 I would like to return the total price sum of the 1240 + 2844 + 9850. This is for an assignment and I just can't seem to figure it out. I tried grouping by the count(eventcode) * price but I get an error for invalid use of group function. Sorry for the badly worded question I am just frustrated. Thanks for any help!
If you want the total price for each eventcode, then that should be in the group by:
select eventcode, sum(price), min(showdate), max(showdate)
from ticket
group by eventcode;
Notes:
This returns one row per eventcode. That is how group by works.
You want the total price, so that is sum(price).
You don't want any columns in the select that are not in the group by and not arguments to aggregation functions. Hence, no , price.

query optimization with multiple sub-queries

I want to retrieve data
number of meters in this month, minus the number of meters in the previous month,
and the value of the meter is deducted in accordance with their respective codes.
then summed the whole.
there are about 8000 records.
but I try to take 5 records, and it takes time 2:53 sec,
100 records takes time (1 min 1:57 sec).
really matter .
I have query like this.
SELECT code hvCode,
IFNULL( (SELECT meter
FROM bmrpt
WHERE waktu_foto LIKE '2014-05%'
GROUP BY code HAVING code = hvCode),0 )
-IFNULL( (SELECT meter
FROM bmrpt WHERE waktu_foto LIKE '2014-04%'
GROUP BY code HAVING code = hvCode),0 )hasil
FROM bmrpt group by code;
does anybody have an idea to change the query to be optimized?
this the sqlfiddle http://www.sqlfiddle.com/#!2/495c0/1
best regards
though your question is unclear but try below subquery , as what I understand
SELECT COALESCE(SUM(`meter`),0) FROM table WHERE code ='hvCode' AND MONTH(`date_column`) = 5
-
SELECT COALESCE(SUM(`meter`),0) FROM table WHERE code ='hvCode' AND MONTH(`date_column`) = 4

MySQL - How to query for an aggregate count value with a time interval

I am trying to write a single MySQL query which will tell me the total number of active users in the database in week-based intervals. The 2 returned values per row should be the date, and the total number of active users on that date. I was able to get this far:
SELECT from_days(to_days(cast(u.created as datetime)) - mod(to_days(cast(u.created as datetime)) - 1 - 1, 7)) AS date, COUNT(1) as count
FROM users u
WHERE u.active = 1
GROUP BY 1;
I believe this shows me the number of new active users in each given interval, but I can't figure out how to 'aggregate' those counts to show the total number of users increasing over each time interval. Any point in the right direction would be greatly appreciated.
It's hard to say without an example of your output but I would start by making the whole thing a subquery and using an aggregate function or a calculation on top of it.
See this post:
MySQL Running Total with COUNT