select sum where sum - mysql

I want to select some entries based on a max+sum condition.
mytable
----------
id | col1 | col2
I want to select all entries that have the sum of col1 & col2 greater than or equal to the max of sum minus X. (don't ask me why :) )
So far I managed to get the sum OK (hereafter aliased as "total") with:
SELECT id,SUM(col1 + col2) AS total FROM mytable GROUP BY id;
I also managed to get the MAX of the sum OK (with a ORDER BY/LIMIT workaround though):
SELECT id,SUM(col + col) as total FROM mytable GROUP BY id ORDER BY total DESC LIMIT 1;
However everytime I try to re-use my alias as a condition (e.g. WHERE total >= ...) I get an "Unknown column" error
Anything would be greatly appreciated

You have some misconceptions about SUM. SUM is an aggregating function, means it works on many records and not just one.
To calculate the sum of two fields per record, you should use only the + operator.
SELECT id, col1+col2 AS 'total'
FROM T1
WHERE
(col1+col2+x) >=(SELECT MAX(col1+col2) from T1)

If you are using group by, you'll need to use a having clause:
SELECT id,SUM(col1+col2) as total FROM mytable GROUP BY id ORDER BY total HAVING total >= x

Related

Finding the average of a column with a variable condition in the where clause

Suppose I have a table named Data:
id
value
1
4
2
8
.
.
.
.
.
.
50
10
And I want to find the first 'id' index (nFirst) where the average of the 'value' column is above some pre-given value ('avg'). In other words I want to solve for nFirst. I have this query
SELECT AVG(value)
FROM Data
WHERE id < nFirst AND AVG(value) > avg
GROUP BY id;
The above query has the general idea of what I'd like to calculate but it obviously won't work. Any ideas?
For MySql 8.0+ use AVG() window function to get the running average for each row and filter out the rows with less than the average that you want and finally pick the smallest id of the results:
SELECT *
FROM (
SELECT id, AVG(value) OVER (ORDER BY id) avg_value
FROM Data
) d
WHERE avg_value > ?
ORDER BY id LIMIT 1;
For previous versions use a self join and aggregation:
SELECT d1.id, AVG(d2.value) avg_value
FROM Data d1 INNER JOIN Data d2
ON d2.id <= d1.id
GROUP BY d1.id
HAVING avg_value > ?
ORDER BY d1.id LIMIT 1;
Replace ? with the average value that you want.
If you have DB version 8.0+, then use SUM() OVER () window function, presuming all id values are consecutively incrementing as in the shared example data set, in such a way
SELECT MIN(id) AS least_id
FROM
(SELECT id, SUM(value) OVER (ORDER BY id)/id AS avg_
FROM Data) AS d
WHERE avg_ > avg --> substitute 5 as an example value for the parameter "avg"
Demo

Sql - Query to get total number of records in table

I have table like this
enter image description here
I need to get the data only whose age > 10, along with that i need to get the total number of records present in the table. ie. in this example it is 4 records. what i need is in single query i need to get the total number of records present in table and columns which i query.
Query will be somewhat like
SELECT ID, NAME, count(TOTAL NUMBER OF RECORDS IN TABLE) as Count from MYTABLE WHERE AGE > 10
Any idea about this ?
You can use a subquery in the FROM clause:
SELECT ID, NAME, c.cnt as Count
FROM MYTABLE CROSS JOIN
(SELECT COUNT(*) as cnt FROM MYTABLE) c
WHERE AGE > 10 ;
Both databases support window functions, but they are not really helpful here, because the count is not filtered in the same way as the outer query. If you do want the filter for both, then in the most recent versions you can do:
SELECT ID, NAME, COUNT(*) OVER () as cnt
FROM MYTABLE
WHERE AGE > 10 ;
You can try below - using scalar subquery
SELECT ID, NAME, age,(select count(*) from mytable WHERE AGE > 10) as Count
from MYTABLE
WHERE AGE > 10

Aggregate function in BETWEEN and AND

I have joined 3 tables in my query. In my Inventory db,Price is taken from table c and quantity is taken from table b. How can I show the records list of users who have ordered between the given value and maximum value of the column.
I am using below query in mysql to retrieve records. As expected it shows error. Any help will be highly appreciated
SELECT .... GROUP BY userid HAVING SUM(c.`price` * b.`quantity`) BETWEEN 9000 AND MAX(SUM(c.`price` * b.`quantity`))
If I understand correctly you don't need BETWEEN. Try it this way
SELECT ....
GROUP BY userid
HAVING SUM(c.`price` * b.`quantity`) >= 9000
In case you wondered you can't chain aggregate functions. And even if you could it wouldn't make sense because you group by userid, but trying to get MAX of SUM from all users. In order for this to work you should've used a subquery to get max value e.g.
SELECT ....
GROUP BY userid
HAVING SUM(c.`price` * b.`quantity`) =
(
SELECT MAX(total) total
FROM
(
SELECT SUM(c.`price` * b.`quantity`) total
GROUP BY userid
) q
)

How to select data where a field has a min value in MySQL?

I want to select data from a table in MySQL where a specific field has the minimum value, I've tried this:
SELECT * FROM pieces WHERE MIN(price)
Please any help?
this will give you result that has the minimum price on all records.
SELECT *
FROM pieces
WHERE price = ( SELECT MIN(price) FROM pieces )
SQLFiddle Demo
This is how I would do it, assuming I understand the question.
SELECT * FROM pieces ORDER BY price ASC LIMIT 1
If you are trying to select multiple rows where each of them may have the same minimum price, then #JohnWoo's answer should suffice.
Basically here we are just ordering the results by the price in ascending order (ASC) and taking the first row of the result.
This also works:
SELECT
pieces.*
FROM
pieces inner join (select min(price) as minprice from pieces) mn
on pieces.price = mn.minprice
(since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)
Use HAVING MIN(...)
Something like:
SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
Efficient way (with any number of records):
SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
In fact, depends what you want to get:
- Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces
WHERE price = ( SELECT MIN(price) FROM pieces)
ORDER BY stock ASC
To improve #sberry's answer, if the column has a null value then simply doing ORDER BY would select a row with null value. Add a WHERE clause to get correct results:
SELECT * FROM pieces
WHERE price>0
ORDER BY price ASC
LIMIT 1;
Or if there is a chance of having negative values and/or VARCHAR, etc. do:
SELECT * FROM pieces
WHERE price IS NOT NULL
ORDER BY price ASC
LIMIT 1;
To make it simpler
SELECT *,MIN(price) FROM prod LIMIT 1
Put * so it will display the all record of the minimum value

SQL Work out the average time difference between total rows

I've searched around SO and can't seem to find a question with an answer that works fine for me. I have a table with almost 2 million rows in, and each row has a MySQL Date formatted field.
I'd like to work out (in seconds) how often a row was inserted, so work out the average difference between the dates of all the rows with a SQL query.
Any ideas?
-- EDIT --
Here's what my table looks like
id, name, date (datetime), age, gender
If you want to know how often (on average) a row was inserted, I don't think you need to calculate all the differences. You only need to sum up the differences between adjacent rows (adjacent based on the timestamp) and divide the result by the number of the summands.
The formula
((T1-T0) + (T2-T1) + … + (TN-TN-1)) / N
can obviously be simplified to merely
(TN-T0) / N
So, the query would be something like this:
SELECT TIMESTAMPDIFF(SECOND, MIN(date), MAX(date)) / (COUNT(*) - 1)
FROM atable
Make sure the number of rows is more than 1, or you'll get the Division By Zero error. Still, if you like, you can prevent the error with a simple trick:
SELECT
IFNULL(TIMESTAMPDIFF(SECOND, MIN(date), MAX(date)) / NULLIF(COUNT(*) - 1, 0), 0)
FROM atable
Now you can safely run the query against a table with a single row.
Give this a shot:
select AVG(theDelay) from (
select TIMESTAMPDIFF(SECOND,a.date, b.date) as theDelay
from myTable a
join myTable b on b.date = (select MIN(x.date)
from myTable x
where x.date > a.date)
) p
The inner query joins each row with the next row (by date) and returns the number of seconds between them. That query is then encapsulated and is queried for the average number of seconds.
EDIT: If your ID column is auto-incrementing and they are in date order, you can speed it up a bit by joining to the next ID row rather than the MIN next date.
select AVG(theDelay) from (
select TIMESTAMPDIFF(SECOND,a.date, b.date) as theDelay
from myTable a
join myTable b on b.date = (select MIN(x.id)
from myTable x
where x.id > a.id)
) p
EDIT2: As brilliantly commented by Mikael Eriksson, you may be able to just do:
select (TIMESTAMPDIFF(SECOND,(MAX(date),MIN(date)) / COUNT(*)) from myTable
There's a lot you can do with this to eliminate off-peak hours or big spans without a new record, using the join syntax in my first example.
Try this:
select avg(diff) as AverageSecondsBetweenDates
from (
select TIMESTAMPDIFF(SECOND, t1.MyDate, min(t2.MyDate)) as diff
from MyTable t1
inner join MyTable t2 on t2.MyDate > t1.MyDate
group by t1.MyDate
) a