How do i count and sum the values from the database - php

I have a table in mysql which holds the values in integers, my table is something like this.
I want to sum up the values of a particular column, for example i want to calculate the total amount, total cashpaid and total balance. hwo do i do it?

Use SUM() function of MySQL like this:
select SUM(amount) from tablename;
select SUM(cashpaid) from tablename;
select SUM(balance) from tablename;
OR you can group them into one:
select SUM(amount), SUM(cashpaid), SUM(balance) from tablename;

if you want to do it in one single query:
SELECT SUM(amount) as total_amount, SUM(cashpaid) as total_paid,SUM(balance) as total_balance FROM tablename;
to count element use COUNT()
SELECT COUNT(*) FROM tablename;
it's better to use aliases for the column names when using this functions.

Try out this:
select SUM(amount) AS total_amount, SUM(cashpaid) AS total_cashpaid, SUM(balance) AS total_balance from tablename;

try
select sum(amount), sum(cashpaid), sum(balance) from tablename

For counting the total number of records use count() function.
like:
select count(amount) from table_name;
It will return from above table in your question 3.
For Sum Use SUM() in SELECT query.
Like:
select SUM(amount) as total_amount,SUM(cashpaid) as total_cash_paid,SUM(balance) as total_balance from table_name;
after as is your new column name which will automaticaly create after executing of query.

Related

Combine SQL statement

I would like to select different column from different row from the same table with one statement . How will I combine this to be one?
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
You could just use each of two current queries as subqueries in one select statement:
SELECT
(SELECT shop_lat_log FROM customers WHERE phoneNumber = '254719401837') AS shop_lat_log,
(SELECT delivery_lat_log FROM customers WHERE phoneNumber = '25472054919') AS delivery_lat_log
FROM dual;
This assumes that each of your two queries returns a single value. If not, then perhaps a UNION would be more appropriate:
SELECT
shop_lat_log AS log_value,
'shop_lat_log' AS log_type
FROM customers
WHERE phoneNumber = '254719401837'
UNION ALL
SELECT
delivery_lat_log,
'delivery_lat_log'
FROM customers
WHERE phoneNumber = '25472054919'
You can use a UNION for that:
SELECT `shop_lat_log` FROM `customers` WHERE `phoneNumber`='254719401837'
UNION
SELECT `delivery_lat_log` FROM `customers` WHERE `phoneNumber`='25472054919'
Note that the second query must have the same number of columns as the first query, and the results will have the first query's column names.
So even though you're selecting the delivery_lat_log column in your second query, the results will be in the shop_lat_log column if you're fetching an associative array.
Use an SQL case statement
select case c.phone_number
when '254719401837'
then c.shop_lat_log
when '25472054919'
then c.delivery_lat_log
end as field
from customer as c
where c.phone_number in ('254719401837', '25472054919')

Display records only if its belongs from table(1) in PHP

i have 2 tables which are join together with the help of UNION and display the records using single while loop.
problem:
now the problem is i want do display records from table(1) and table(2) separately but condition is using only single while loop.
here is the SQL:`
$sql = "(SELECT * FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to') UNION (SELECT * FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')";
is there any way to do it?.sorry to say but i am new to PHP.
any advise is appreciated.
Just add a field to both sides of the query:
(SELECT *, 'subject_first' as `table` FROM subject_first WHERE date BETWEEN '$user_from' AND '$user_to')
UNION
(SELECT *, 'subject_second' as `table` FROM subject_second WHERE date BETWEEN '$user_from' AND '$user_to')
ORDER BY `table`
I added the order by part so you can insert a <br> or whatever to split the results.

Select most common value? [duplicate]

How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1

fetch column2 value corresponding to column1 maximum,minimum?

Is it possible to fetch column2 values for max(column1). help me. I got to find the date corresponding to the max(price) and min(price) in database.
$str="select MAX(psq_price),MIN(psq_price),AVG(psq_price) from crawl_archives where p_id=2570";
I found max , min values from this query.. Need to find the date column corresponding to the maximum price ..
try this
select date , MAX(psq_price),MIN(psq_price)
from mytable
group by date
try something like this:
select *
from <table> t
join (select max(price) as max_price
from <table>
group by <col1>
)a
on a.col1=t.col1
and a.max_price=t.price

MySQL query record with max value in a specific column

I know that this must be a very basic question, but I've not found an answer.
As the title says, I would like the query the record that holds the max value of a specific column.
I use the following code to achieve that:
SELECT * FROM `table_name` ORDER BY `column_with_specific_max_value` DESC LIMIT 1
I would like to know if there is an other way to achieve the same result (more parsimonious)? I know that SQL has a function MAX(column) but it's not working the way I want. I tried this:
SELECT * FROM `table_name` WHERE `column_with_specific_max_value`=MAX(`column_with_specific_max_value`)
and this:
SELECT *, MAX(`column_with_specific_max_value`) FROM `table_name`
What happen if the column_with_specific_max_value has 2 rows with the same max value? will it return both rows?
What about?
select * from table1
where score in (select max(score) from table1)
Or even without a max:
select * from table1
where score >= all (select score from table1)
Any of those WILL return all rows with the max value. You can play with it here.
If your table has an auto-increment column to work with, you could do something like...
select
YT3.*
from
( select
MAX( YT2.AutoIncColumn ) as ReturnThisRecordID
from
( select max( YT1.WhatColumn ) as MaxColumnYouWant
from YourTable YT1 ) JustMax
Join YourTable YT2
on JustMax.MaxColumnYouWant = YT2.WhatColumn ) FinalRecord
JOIN YourTable YT3
on FinalRecord.ReturnThisRecordID = YT3.AutoIncColumn
I would also ensure this is a column that SHOULD have an index on it, otherwise, you'll always be doing a table scan.

Categories