SQL SUM values from column and dividide by number of rows - php

I'm trying to calculate a percentual...and I need to sum all values from a column (Its already ok) but I need divide the result by number of rows...
select sum(voto) from tablename where id = numberHere

use COUNT to get the totalNumber of rows.
SELECT SUM(voto) / (COUNT(*) * 1.0)
FROM tablename
WHERE id = numberHere
by adding * 1.0 on the query will allow decimal places on the result.
or simply as
SELECT AVG(voto)
FROM tablename
WHERE id = numberHere

JW's answer is correct if you're looking specifically to do it by Summing/Dividing, but SQL has a function for that.
SELECT AVG(voto) FROM tablename WHERE id = numberHere
AFAIK, it automatically returns the same type as you input (except date columns, which should be parsed to seconds then re-encoded to date).

AVG should work, count(*) should work, you can also use ##rownum to get the number of rows returned by the statement if you need to do more with that number.

Related

How to find the nearest string value from table?

I have a table name "test" having a column code (string format) and data is like:
U298765
U298799
U210430
U210499
B239856
Now I want to get data by input field entry. If a user write U298750, I want show the nearest value U298765 and for U210401,U210430.
You can use the right function to fetch the number and then use following logic.
Select t.*
From test t
Order by abs(Right(code, length(code)-1) - Right(your_input, length(your_input)-1))
Limit 1
I am consodering that you need the nearest based on numbers only.
Try below query:
select code from test
order by abs(abs(substring(code,2,length(code)))-abs(substring('U298750',2,length('U298750'))))
Limit 1
In place of 'U298750' use your input
You seem to just want:
select t.*
from t
where code >= ? -- the input value
order by code desc
limit 1;
The ordering of strings alphabetically is sufficient for getting the "next" value after the string. There is no need to convert anything to numbers.

How to target specific rows returned by mysqli query

Let's say I have a table with following columns: id-1, id-2, col-1, col-2, col-3
Here, id-1 is the primary key and is auto-incremented. id-2 is a different id and is not necessary to be unique. There are multiple instances of same id in that column. col-1, col-2, col-3 are just necessary columns.
I pass a query to select data from the table.
mysqli_query($connect, SELECT * FROM table WHERE id-2='some_specific_id')
It will return multiple rows. I would like to know how can I target specific rows, say row number 3.
First, use ":
mysqli_query($connect, "SELECT * FROM table WHERE id-2 = 'some_specific_id'");
Target specific row? Do you mean to limit the fetched rows? Or get the 3rd row?
For limiting the fetched rows, you can use LIMIT:
SELECT * FROM table WHERE id-2='some_specific_id' LIMIT 3
For getting the third row:
SELECT * FROM table WHERE id-2='some_specific_id' LIMIT 2, 1
Well although it seems you just rather needed to learn basic SQL to get your answer, there is still the question in the title, that may attract other people whose problem is formulated exactly like that. So goes the answer:
Mysqli is not very convenient for this task, so we would use PDO.
In case your query is intended to return multiple rows and you need to address one of them by number (which is rather makes little sense, but anyway), use fetchAll() method:
$stmt = $connect->prepare("SELECT * FROM table WHERE id2=?");
$stmt->execute(['some specific id']);
$data = $stmt->fetchAll();
and you will be able to address returned rows by number, starting from zero:
echo $data[0]['col1'];
However, it makes more sense to address the returned rows by some unique id. In this case just add this unique field fiset in the field list and then use the special PDO street magic:
$stmt = $connect->prepare("SELECT id1, table.* FROM table WHERE id2=?);
$stmt->execute(['some specific id']);
$data = $stmt->fetchAll(PDO::FETCH_UNIQUE);
and you will be able to address returned rows by that unique field :
echo $data[$id1]['col1'];
Use LIMIT to get what you want like:
SELECT * FROM table WHERE id-2='some_specific_id' LIMIT 2, 1;
Or, if you want to fetch from array, then use the 3rd index of array.
LIMIT Explanation:
The following illustrates the LIMIT clause syntax with two arguments:
SELECT
column1,column2,...
FROM
table
LIMIT offset , count;
Let's examine the LIMIT clause parameters:
The offset specifies the offset of the first row to return. The offset of the first row is 0, not 1.
The count specifies the maximum number of rows to return.

Counting all rows with a limit

I need to filter (using where clauses) the rows in my table, count the total number of rows from this filter and then limit number of rows for pagination.
What is quickest/more efficient?
Count the rows with sql query. Select the rows with a limit with sql query.
Select all rows with sql query. Count the array with PHP. Split the array with PHP.
Or is there another way to count all rows and get a limited set of the results out?
You should use SQL_CALC_FOUND_ROWS and the FOUND_ROWS() function to return the total number of rows even when a LIMIT is applied to the returned results. After you run your query the results will be returned, and then you can run SELECT FOUND_ROWS() to return the total number of rows without having to run the query again.
SELECT SQL_CALC_FOUND_ROWS * FROM my_table WHERE column = 'something' LIMIT 10;
SELECT FOUND_ROWS() AS total_results;
Use two queries, one to retrieve total number of rows, another to get the rows. The first argument in LIMIT clause specifies the offset of the first row ( current_page * post_per_page ), and the second specifies the maximum number of rows to return ( post_per_page ).
SELECT COUNT(*) AS num_rows FROM table;
SELECT * FROM table LIMIT start, length;
The MySQL LIMIT should do the trick for you. This is a more efficient approach, as it helps in fetching only the relevant records to be displayed and nothing else.
Note that the startingIndex, numberOfRecordsPerPage variables should be set before executing the query.
SELECT * FROM MY_TABLE where
(...) //ALL CONDITIONS go here
LIMIT startingIndex, numberOfRecordsPerPage;
From the MySQL Reference
With two arguments, the first argument specifies the offset of the
first row to return, and the second specifies the maximum number of
rows to return. The offset of the initial row is 0 (not 1):
SELECT * FROM tbl LIMIT 5,10; # Retrieve rows 6-15
In order to identify whether or not to expect any records in return, one must first run the query (with COUNT and without any LIMIT condition):
`SELECT COUNT(*) FROM MY_TABLE where (...) //ALL CONDITIONS go here`
and store it separately. This shall be the total records applicable to the WHERE clauses given.
If the sum startingIndex+numberOfRecordsPerPage is >= TOTAL_COUNT then that paginated set shall be the last of the whole list and the user should not be allowed to click the NEXT button.
PS: Also, as pointed out in the comments, you might want to look at a framework alternative, like Criteria API for Java, to the heavy weightlifting, particularly if your WHERE conditions are also generated dynamically.

how to get highest integer value from mysql table PHP

how to get highest integer value from mysql table PHP
$getingstoredata=mysql_query('select number from number ');
while ($getstd=mysql_fetch_row($getingstoredata)){
print_r($getstd);
}
and table stricture is same like this image http://fastcoding.tk/table.png
i want to display highest integer value for example it 120 is highest value in this table
use MAX()
SELECT MAX(number) FROM number
You can simply use the Aggregate Functions.
SELECT MAX(field_name) FROM table_name GROUP BY field_name;
You can also use "order by" clause with DESC and fetch the first row from result-set.
select MAX(number) from number;
MAX() should serve your purpose
If your field is a mixed varchar where some values begin with letters, you can use this solution:
SELECT max(number) FROM table WHERE number REGEXP '^[0-9]+$';
the function max() will take the highest value
the regex sorts out every value that not begins with a number
$hinteger=mysql_query("SELECT MAX(integer) FROM number");

PHP MYSQL - Count & Average In Same Query

This may be very simple but I am trying to do a query that will return the average of the results but I also want it to count the number of rows it used to get the average. For example:
Row 1 = 5
Row 2 = 2
Row 3 = 9
Row 4 = 1
Average = 4.25
Count = 4
Is there a way to do this with one query apposed to two. When i used the avg function is always just returns one row so my count is 1 instead of 4. I need a query that will average but also tell me how many records it went through.
I am trying to avoid using two queries. Thank you for your help.
This is pretty basic and should have been discoverable via search.
SELECT COUNT(field) as `count`, AVG(field) as `average` FROM table_name
In the terms you have stated - if you aren't GROUPing or things like that - you'd just write
SELECT COUNT(col) AS cnt, AVG(col) AS avg FROM tbl;
and you ought to have no problems. You get one row, with the fields cnt and col containing what you need.
The problem you're having is probably due to the use of mysql_num_rows to get the count, which is not correct.
forgot to add: or to the fact that you did not supplied your whole problem.
You can use multiple aggregate functions in a single query:
SELECT COUNT(*), AVG(field) FROM mytable
SELECT COUNT(*), AVG(YourColumn)
FROM YourTable

Categories