i'm trying to get a sum of a column for each month. this is what i've done.
My SQL Query :
SELECT `ID_Pilot` ,`PilotStationDate` ,`PilotWaitingTime`, ( SELECT FORMAT(SUM( `PilotWaitingTime` ),2) FROM pilot ) AS Total
FROM pilot
this is the result :
ID_Pilot PilotStationDate PilotWaitingTime Total
P001 2013-01-01 0.2 39.20
P002 2013-01-02 19.2 39.20
P003 2013-01-03 7.8 39.20
P004 2013-02-04 6.4 39.20
P005 2013-02-06 5.6 39.20
and this is the result i want :
ID_Pilot PilotStationDate PilotWaitingTime Total
P001 2013-01-01 0.2 27.20
P002 2013-01-02 19.2 27.20
P003 2013-01-03 7.8 27.20
P004 2013-02-04 6.4 12.00
P005 2013-02-06 5.6 12.00
note: 27.20 in Total column is a sum of PilotWaitingTime in January and 12.00 is a sum of PilotWaitingTime in February
Thank you for your help
This query will return the sum for each month:
SELECT
DATE_FORMAT(PilotStationDate, '%Y-%m') as year_month,
FORMAT(SUM( `PilotWaitingTime` ),2) as total
FROM pilot
GROUP BY
DATE_FORMAT(PilotStationDate, '%Y-%m')
then you just can join back this query with the pilot table:
SELECT
p.`ID_Pilot`,
p.`PilotStationDate`,
p.`PilotWaitingTime`,
t.total
FROM
pilot p INNER JOIN (
SELECT
DATE_FORMAT(PilotStationDate, '%Y-%m') as year_month,
FORMAT(SUM( `PilotWaitingTime` ),2) as total
FROM pilot
GROUP BY
DATE_FORMAT(PilotStationDate, '%Y-%m')
) t ON DATE_FORMAT(p.PilotStationDate, '%Y-%m') = t.year_month
Your pilot table data would be helpful to provide the perfect query. But you can try these two queries.
SELECT `ID_Pilot` ,`PilotStationDate` ,`PilotWaitingTime`, ( SELECT FORMAT(SUM( `PilotWaitingTime` ),2) FROM pilot p2 where p2.ID_Pilot = p1.ID_Pilot ) AS Total
FROM pilot p1;
OR
SELECT `ID_Pilot` ,`PilotStationDate` ,`PilotWaitingTime`, FORMAT(SUM( `PilotWaitingTime`),2) AS Total
FROM pilot GROUP BY ID_Pilot;
Here's the query you could try out (Example http://sqlfiddle.com/#!9/96667/1)
select pilot.*, totals.tot
from pilot
inner join
(
select
year(pilotstationdate) as yr,
month(pilotstationdate) as mth,
sum(pilotwaitingtime) as tot
from pilot
group by
year(pilotstationdate),
month(pilotstationdate)
) totals
on year(pilot.pilotstationdate) = totals.yr
and month(pilot.pilotstationdate) = totals.mth
select p.id_pilot, p.pilotstationdate, p.pilotwaitingtime,
(select sum(pilotwaitingtime)
from pilot
where last_day(pilotstationdate)=last_day(p.pilotstationdate)) total
from pilot p
last_day() is a mysql function that returns the last day of the month.
Related
I have these two tables;
trips
id
date
revenue
1
01/01/2020
5000
2
01/01/2020
3000
3
02/01/2020
4000
4
02/01/2020
2000
expenses
id
tripid
amount
1
1
500
2
1
300
3
2
400
4
2
200
5
2
700
I would like to get the sum of revenue collected in a day AND sum of expenses in a day. I have the following sql which gives me results but the sums are entirely wrong.
SELECT i.id, sum(i.revenue) as total, i.date trip , sum(c.amount) as exp, c.tripid expenses FROM trip i INNER JOIN expenses c ON i.id = c.tripid GROUP BY i.date ORDER BY trip DESC
You can preaggregate the expenses by trip, and then aggregate again in the outer query:
select t.date, sum(t.revenue) as revenue, coalesce(sum(e.expense), 0) as expense
from trips t
left join (
select tripid, sum(amount) as expense
from expenses
group by tripid
) e on e.tripid = t.id
group by t.date
I am in big trouble and I need your help, I have two tables sales and recovery. My requirement is to get report month wise so I use date_format in query with Union All, its working fine but the issue is its shows the result in different rows of sale and recovery if the month is same.
Sale:
ID(unique) Party Amount Sale_Date
1 95 1500 01-05-2017
2 97 3500 15-05-2017
3 95 2500 05-06-2017
4 97 500 10-06-2017
5 99 1000 01-07-2017
Recovery:
ID(unique) Party Amount Recovery_Date
1 95 1000 01-06-2017
2 97 2000 20-06-2017
3 95 3500 10-07-2017
4 97 900 10-07-2017
5 99 1500 15-08-2017
I want to get result month wise so I use DATE_FORMAT in query with UNION ALL. below is the query i am using.
"SELECT SUM(amount) as sale_amount, DATE_FORMAT(Sale_Date, '%M %Y'),
null as recovery_amount FROM
`SALE` GROUP BY DATE_FORMAT(Sale_Date, '%M %Y')
UNION ALL
"SELECT null as sale_amount, DATE_FORMAT(Sale_Date, '%M %Y'),
SUM(amount) as recovery_amount FROM
`SALE` GROUP BY DATE_FORMAT(Sale_Date, '%M %Y')
Result:
S.No Month Sale Recovery Balance
1 May-2017 5000 5000
2 June-2017 3000 3000
3 June-2017 3000 -3000
4 July-2017 1000 1000
5 July-2017 4400 -4400
6 Aug-2017 1500 -1500
the above result is ok but i need the result in below format to get correct balance amount
Expected Result:
S.No Month Sale Recovery Balance
1 May-2017 5000 5000
2 June-2017 3000 3000 0
3 July-2017 1000 4400 -3300
4 Aug-2017 1500 -1500
You have to aggregate the resultsof the union by moving it into a subquery:
Select year_month, sum(sale_amount) as sale_amount, sum(recover_amount) as recovery_amount, sum(sale_amount)-sum(recovery_amount) as balance
From (
SELECT SUM(amount) as sale_amount, DATE_FORMAT(Sale_Date, '%M %Y') as year_month, null as recovery_amount
FROM `SALE` GROUP BY DATE_FORMAT(Sale_Date, '%M %Y')
UNION ALL
SELECT null as sale_amount, DATE_FORMAT(recovery_Date, '%M %Y'), SUM(amount) as recovery_amount
FROM `recovery` GROUP BY DATE_FORMAT(recovery_Date, '%M %Y')) as t
Group by year_month
Unfortunately, mysql does not support full outer join hence this beauty above.
i am looking to find the avg cost for the total cost of each order but my grouping function is invalid
SELECT AVG(SUM(quantityOrdered*priceEach)) AS total
FROM orderdetails od
GROUP BY orderNumber
below is a snippet of my database
orderNumber productCode quantityOrdered priceEach orderLineNumber
10100 S24_3969 49 35.29 1
10101 S18_2325 25 108.06 4
10101 S18_2795 26 167.06 1
10101 S24_1937 45 32.53 3
10101 S24_2022 46 44.35 2
10102 S18_1342 39 95.55 2
10102 S18_1367 41 43.13 1
10103 S10_1949 26 214.3 11
10103 S10_4962 42 119.67 4
10103 S12_1666 27 121.64 8
10103 S18_1097 35 94.5 10
10103 S18_2432 22 58.34 2
10103 S18_2949 27 92.19 12
10103 S18_2957 35 61.84 14
10103 S18_3136 25 86.92 13
10103 S18_3320 46 86.31 16
It's invalid use cannot use two aggregate functions together
SELECT SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
Having SUM(quantityOrdered*priceEach)>(SELECT AVG(quantityOrdered*priceEach) FROM orderdetails)
Just calculate the average using sum() divided by a number:
SELECT SUM(quantityOrdered*priceEach) / COUNT(DISTINCT orderNumber) AS total
FROM orderdetails od ;
You do it in two steps.
SQL Fiddle Demo
Calculate the Total of each order.
SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
Calculate the Average between all the totals
SELECT AVG(total)
FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
) T
EDIT: I miss the last step after checking Ritesh answer.
SELECT o.*, t.global_avg
FROM (SELECT orderNumber, SUM(quantityOrdered*priceEach) AS order_total
FROM orderdetails od
GROUP BY orderNumber) o
CROSS JOIN
(SELECT AVG(total) global_avg
FROM ( SELECT orderNumber, SUM(quantityOrdered*priceEach) AS total
FROM orderdetails od
GROUP BY orderNumber
) t
) t
WHERE o.order_total > t.global_avg;
OUTPUT:
I want to select a total sales of each Category
Here is my table: (catNo = Category No. prodNo = product No.)
OrderLine:
prodNo ordNo actualPrice qty
P0001 OR001 3.00 20
P0002 OR002 3.00 2
P0003 OR003 500.00 25
Product:
prodNo prodName prodPrice prodPhoto stockQty catNo suppNo
P0001 OverPower 1500.00 OP_C4_Black.jpg 10 CAT05 S0001
P0002 Vain 300.00 Vain.jpg 5 CAT04 S0002
P0003 test 500.00 test.jpg 40 CAT05 S0001
my SQL command is
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `orderline`.`prodNo`;
What I want is
catNo Total Sales
CAT05 12560.00
CAT04 6.00
What actual output is
catNo Total Sales
CAT05 60.00
CAT04 6.00
CAT05 12500.00
How can I display the total sales of each Category?
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `catNo`;
Try this, I hope it helps.
Instead of grouping by product number you should be grouping by category number:
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `Product`.`catNo`;
Group by catNo. Then you will get the desired result:
SELECT `catNo` , sum(`actualPrice`*`qty`)as `Total Sales`
FROM `orderline` , `product`
WHERE `orderline`.`prodNo` = `product`.`prodNo`
GROUP BY `catNo`
Result:
catNo Total Sales
-------------------
CAT04 6
CAT05 12560
Sample result in SQL Fiddle
I have a cron script that writes the total number of active users to a table every day. I'm trying to now generate a simple report that would show the "high water mark" for each month. Because some accounts expire during the month it's possible the highest number may NOT be at the end of the month.
Here's a sample of my table structure
tblUserLog
-----------
record_id INT(11) // PRIMARY KEY
run_date DATE // DATE RUN
ttl_count INT(11) // TOTAL FOR DAY
Sample data:
record_id run_date ttl_count
1 2013-06-01 500
2 2013-06-10 510
3 2013-06-20 520
4 2013-06-30 515
5 2013-07-01 525
6 2013-07-10 530
7 2013-07-20 540
8 2013-07-31 550
9 2013-08-01 560
What I would like returned is:
record_id run_date ttl_count
3 2013-06-20 520
8 2013-07-31 550
9 2013-08-01 560
I've tried two queries that are close...
// This will give me the total for the first of the month
SELECT s.record_id, s.run_date, s.ttl_count
FROM tblStatsIndividual s
JOIN (
SELECT record_id
FROM tblStatsIndividual
GROUP BY DATE_FORMAT(run_date, '%Y %m')
HAVING MAX(ttl_count)
) s2
ON s2.record_id = s.record_id
ORDER BY run_date DESC
This returns the total for the first of each month, along with the record_id and correct date for the total.
Tried this...
SELECT record_id,max(run_date), max(ttl)
FROM (
SELECT record_id,run_date, max(ttl_count) AS ttl
FROM tblStatsIndividual
GROUP BY DATE_FORMAT(run_date, '%Y %m')
) a
GROUP BY DATE_FORMAT(run_date, '%Y %m')
ORDER BY run_date DESC
This one appears to get the correct "high water mark" but it's not returning the record_id, or the run_date for the row that IS the high water mark.
How do you get the record_id and the run_date for the highest total?
Something like
Select detail.Record_ID, detail.Run_Date, detail.ttl_Count
From tblStatsIndividual detail
Inner Join
(Select Year(run_date) as Year, Month(Run_date) as Month, Max(ttl_count) as ttl
From tblStatsIndividual
Group By Year(run_date), Month(Run_date)) maximums
On maximums.Year = Year(detail.Run_date) and maximums.Month = Month(detail.Run_date)
and maximums.ttl = detail.ttl_count
Should do it. NB based on your requirement if you had two records in the same month with the same (and highest in the month) ttl_count, they would both be returned.
Based on the help from #Tony Hopkinson, This query gets me the info. The one caveat is it shows the ID and date for the first occurrence of the MAX total, so if the total is the same three days in a row on a month, the first day's ID is returned. For my purpose, the last ID would be more ideal, but I can live with this:
SELECT s.Record_ID, s.Run_Date, s.ttl_Count
FROM tblStatsIndividual s
INNER JOIN (
SELECT YEAR(run_date) AS yr, MONTH(run_date) AS mon, MAX(ttl_count) AS ttl
FROM tblStatsIndividual
GROUP BY DATE_FORMAT(run_date, '%Y %m')
) maximums
ON maximums.yr = YEAR(s.run_date)
AND maximums.mon = MONTH(s.run_date)
AND maximums.ttl = s.ttl_Count
GROUP BY ttl_count
ORDER BY run_date DESC