I have two separate queries I am using to pull information for a report. A single year worked fine. However, if a month has more than 1 year it is not showing the correct responses.
Here are my two queries:
select SUM(rpt_complete.total) total, YEAR(bk_schedule.date) as year,zip_codes.zip_code
from rpt_complete
left join bk_schedule on rpt_complete.bk_id = bk_schedule.id
left join users_info on bk_schedule.users_info_id = users_info.id
left join zip_codes on users_info.zip_code = zip_codes.zip_code
group by zip_codes.zip_code, YEAR(bk_schedule.date)
select SUM(rpt_complete.total) total, MONTH(bk_schedule.date) as month, zip_codes.zip_code
from rpt_complete
left join bk_schedule on rpt_complete.bk_id = bk_schedule.id
left join users_info on bk_schedule.users_info_id = users_info.id
left join zip_codes on users_info.zip_code = zip_codes.zip_code
group by zip_codes.zip_code, MONTH(bk_schedule.date)
Then I loop through the results of month as such (and include year in the loop):
#foreach($month_total as $month)
<tr>
<td>{{ $month->zip_code }}</td>
<td>{{ $month->month }}</td>
<td>${{ $month->total }}</td>
<td>
#foreach($year_total as $year)
#if($month->zip_code == $year->zip_code)
{{ $year->year }}
#endif
#endforeach
</td>
<td>
#foreach($year_total as $year)
#if($month->zip_code == $year->zip_code)
${{ $year->total }}
#endif
#endforeach
</td>
</tr>
#endforeach
So if I have a total for December 2014 & December 2015 and my table is filtering on December 2014...December 2014 & 2015 will show in those results.
I guess I am having a hard time trying to figure out how to process the month and year to where it sums the data together.
EDIT: This is MySQL. Specifically I am using Laravel to output my SQL.
Here is my table: http://i.imgur.com/RClRDaW.png
as you can see 36066 has two entries due to being in two different months: However, they are also in 2 separate years. The year part is what is throwing my table off. You can see it's calculating it all together rather than just by month and totaling the year for that months entry.
My expected results are for 36066 1 month (January) to only show 2017 with that total and 36066 10 month (october) to only show the 2016 with that years total since those are the years that those two months belong to.
So, I need the results to look like this: http://i.imgur.com/jlFhR7x.png
I hope that provides so clarity.
add YEAR(bk_schedule.date) into the GROUP BY of your 2nd query
group by zip_codes.zip_code, MONTH(bk_schedule.date), YEAR(bk_schedule.date)
if you got error just include
YEAR(bk_schedule.date)
into your select fields
Try this:
SELECT
zip_codes.zip_code,
substr(bk_schedule.`date`, 1,7) AS ym,
SUM(rpt_complete.total) AS total
FROM ...
LEFT JOIN ...
GROUP BY 1,2
Updated:
If you want both year and year-month shown on same line, better use script to loop, OR use results from 2 SQLs and display togather. Otherwise try the following example (Which is not not encouraged):
SELECT y.geo, ym.ym, y.hit year_hit, ym.hit month_hit
FROM (
SELECT geo,year(ymd) y,sum(hit) hit FROM log_ip_hit
WHERE geo in ('US','CN')
AND ymd BETWEEN '2015-07-01' AND '2016-03-31'
GROUP BY 1,2
) AS y
JOIN (
SELECT geo,substr(ymd,1,7) ym,sum(hit) hit FROM log_ip_hit
WHERE geo in ('US','CN','AU')
AND ymd BETWEEN '2015-07-01' AND '2016-03-31'
GROUP BY 1,2
) AS ym ON y.geo = ym.geo AND y.y = substr(ym.ym,1,4)
After reading your updated question, I think the following is the best solution:
SELECT
zip_codes.zip_code,
year(bk_schedule.`date`) AS y,
substr(bk_schedule.`date`, 5,2) AS m,
SUM(rpt_complete.total) AS total
FROM ...
LEFT JOIN ...
GROUP BY 1,2,3
And when you display the result, use loop and sum based on year + zip.
Related
I have created a database of kittens where I need to use the following formula. In this regard I have two tables: birth and disposal.
Birth table contains id, dob, owner, date of purchase
disposal table contains id, date of disposal (dodisposal), cause of death, sold, treatment
I am now trying use a formula for the two table using the following MySQL query but it is not working.
Select birth.owner, (((select count(disposal.id) from disposal WHERE
dodisposal BETWEEN DATE_SUB(NOW(), INTERVAL 600 DAY) AND NOW()) /
(select count(birth.id) from birth where birth.id not in
(select disposal.id from disposal)
)
) * 100)
from birth left join disposal on
disposal.brandnumber = birth.id group by birth.owner
but I keep getting same results for all owners:
ie
rita : 79.6
sunita : 79.6
Smith : 79.6
The result I am expecting should be through the following formula:
Number of deaths in the current year / total number of live cats * 100
I found a solution to this problem by making two separate views and then their results using a MySQL query.
create view cats as select id, count(disposal.id) from disposal WHERE
dodisposal BETWEEN DATE_SUB(NOW(), INTERVAL 600 DAY) AND NOW()) as dead
create view livecates as select count(birth.id) from birth left join disposal on disposal.id = birth.id where birth.id not in (select disposal.id from disposal) as live
select livecats.id, (dead/live * 100) from livecats left join cats on livecats.id = cats.id group by livecats.id
I have two tables:
table 1.a
id--entry_date-amount
============================
2---2016-04-14--$400
3---2016-04-14--$400
4----2017-07-14--$200
5---2017-07-14--$500
6---2017-05-14--$600
7----2017-06-18--$100
table 2.b
id--entry_date
===========================
2---2016-04-14--$230
3---2016-04-14--$230
4----2017-07-14--$567
5---2017-07-14--$600
6---2017-05-14--$560
7----2017-06-18--$90
8---2016-04-14--$100
from the two tables how can i get count with montwise
my desired result:
month_name--total(count form table a)--total(count form table b)--amount(table a)--amount(table b)
========================================================
April,16-----------2-------------------3---$800-$500
May,17-----------1-------------------1 --$600--$700
June,17-----------2-------------------2--$100--$800
July,17-----------2-------------------2---$700-$400
this is the demo data.
I want to show data from two tables in a single query month wise.
How can i do this?
I tried:
SELECT MONTHNAME(r.entry_date),r.a_total FROM(
SELECT
IFNULL((SELECT COUNT(tr.id) AS amount FROM a AS tr WHERE MONTH(tr.entry_date)=MONTH(t.entry_date)),0) AS a_total
,t.entry_date
FROM(SELECT tr.id,tr.entry_date
FROM a AS tr
WHERE DATE(tr.entry_date) BETWEEN '2017-07-01' AND '2018-06-30') t
GROUP BY MONTH(t.entry_date)) r
But takes 58 seconds for simple query. How can i make this in a simple query?
You can get the counts and sum from each table individually, then use UNION to combine the two result sets into one result set. Something like this :
SELECT Month_name,
SUM(aCount) AS aCount,
SUM(bCount) AS bCount,
SUM(aAmount) AS aAmount,
SUM(bAmount) AS bAmount
FROM
(
SELECT
MONTHNAME(a.entry_date) AS Month_name,
COUNT(a.id) AS aCount,
0 AS bCount,
SUM(a.amount) AS aAmount,
0 AS bAmount
FROM a
GROUP BY MONTHNAME(a.entry_date)
UNION ALL
SELECT
MONTHNAME(b.entry_date) AS Month_name,
0 AS aCount,
COUNT(b.id) AS bCount,
0 AS aAmount,
SUM(b.amount) AS bAmount
FROM b
GROUP BY MONTHNAME(b.entry_date)
) AS t
GROUP BY Month_Name;
live demo
user9131497 has a good design for the big picture. However, I would suggest stuff like this for handling the dates:
SELECT DATE_FORMAT(entry_date, "%M,%y") AS 'Month',
COUNT(*) AS 'aCount'
FROM a
GROUP BY LEFT(entry_date, 7) -- eg, "2017-03"
Try that to see what I mean.
Note that this will work beyond a year. Or did you need January values from all years to be combined?? -- That's what your solution and user9131497's will do. Mine keeps them separate.
Maybe someone could really help me here. I need some guidance. How come when I try to do a SUM in a column from a JOIN table the SUM form the main table returns wrong results? Let's say if sum from table A is 6 but there are 3 records that join with table B then the results turns from 6 to 18.. I just can't seem to get it. Thank you
SELECT SUM(tm_hours) AS total_hours,
SUM(drive_time) AS drive_time,
STR_TO_DATE(CONCAT(YEAR(tm_date),WEEK(tm_date),' Monday'), '%X%V %W') AS weeks
FROM `bhds_timecard`
LEFT JOIN bhds_mileage
ON bhds_timecard.case_no = bhds_mileage.case_no
WHERE bhds_timecard.ds_id = '3' AND tm_date BETWEEN '2016-03-16' AND '2016-03-31'
GROUP BY CONCAT(YEAR(tm_date), WEEK(tm_date))
Output should look something like that I modified the query but I am still getting wrong drive time. drive time for the firs week should be 55 that is because it is only taking the drive time from one day
Try the following:
SELECT SUM(hours) as total_hours, SUM(drive_time), weeks
FROM ( SELECT tm_hours AS hours,
SUM(drive_time) AS drive_time,
STR_TO_DATE(CONCAT(YEAR(tm_date),
WEEK(tm_date),' Monday'), '%X%V %W') AS weeks,
bhds_timecard.case_no
FROM `bhds_timecard`
LEFT JOIN bhds_mileage
ON bhds_timecard.case_no = bhds_mileage.case_no
WHERE bhds_timecard.ds_id = '3'
AND tm_date BETWEEN '2016-03-16' AND '2016-03-31'
GROUP BY weeks, bhds_timecard.case_no
) as innersums
GROUP by weeks;
I have to join three tables.
1 table is transaction , next table is shops, 3rd is weather.
I want to fetch data from all of these three ,but in case of weather table > id,tamp_c,datetime column name .
The query is:-
select HOUR(transaction.time) as Hour ,
TRUNCATE(sum(transaction.total),2) as Total_Sales,
shops.gstIncludedSales as GST_Inc_Sales,
shops.gstFreeSales as GST_Free,weather.temp_c
from transaction,shops,weather
where transaction.shopid=shops.id and transaction.shopid=7
and transaction.transaction_date ='2015-05-25'
group by hour
ORDER BY hour DESC
The problem is that I want to apply a where clause with weather.datetime table separation for particular date like time(datetime)='2015-05-25', but it's not working.
Try this:
WHERE transaction.transaction_date >= '2015-05-25' AND transaction.transaction_date < '2015-05-26'
That will return rows with timestamp during the whole day (midnight until midnight - time is implied).
If you have SQLServer 2014 you canm use DATE(transaction.transaction_date).
Does this do what you want
SELECT HOUR(transaction.time) as Hour ,
TRUNCATE(sum(transaction.total),2) as Total_Sales,
shops.gstIncludedSales as GST_Inc_Sales,
shops.gstFreeSales as GST_Free,weather.temp_c
FROM transaction
JOIN shops ON transaction.shopid=shops.id
JOIN weather ON DATE(transaction.transaction_date) = DATE(weather.datetime)
WHERE DATE(transaction.transaction_date)='2015-05-25' AND transaction.shopid=7
GROUP by hour
ORDER BY hour DESC
(Assuming you are using MySQL)
I've got two tables in MySql
1 (Staff): Id/Name/SecondName
2 (fee):
Id/StaffId/Date(yyyy-mm-dd)/HoursWorked(hh:mm)/fee(int)/workType
There is also a script adding records to fee table.
I'm trying to group data in php to create html table like:
Name, Second Name | January 2009 | 123:45 hours | 2100,00 USD
February 2009...
March 2009 ....
Next person... etc.
So generally I'm trying to sum fee and hours in specific month and print a report from database...
And I need some advice/help... What is the bast way to create table like this?
Maybe something like this? Not tested though...
SELECT s.Name, s.SecondName, CONCAT(DAYOFMONTH(f.Date),', ',YEAR(f.Date)),
SUM (f.HoursWorked), SUM(f.Fee)
FROM Staff s
JOIN Fee f ON f.StaffId = s.Id
GROUP BY s.Id, YEAR(f.Date), MONTH(f.Date)
Edit: Ofcourse you need to group on s.Id...
That's not the best way, but if you want to do it with one query (it's easy to export to Excel):
SELECT
s.Name,
s.SecondName,
DATE_FORMAT('%M %y', f.`Date`),
SEC_TO_TIME( SUM( TIME_TO_SEC( `HoursWorked` ) ) ) as TotalHours,
sum(fee) AS TotalFee
FROM
Staff AS s
INNER JOIN fee AS f on s.id = f.StaffId
WHERE
1
GROUP BY s.id, YEAR(f.`Date`), MONTH(f.`Date`)
You cal also query stuff:
// that's not a real function, just get all Staff into $staff
$staff = QueryRows(SELECT * FROM Staff);
and then query fee:
foreach($staff as $s){
// use this query to query statistics
SELECT * FROM fee
WHERE StaffId = $s['id']
GROUP BY StaffId, YEAR(f.`Date`), MONTH(f.`Date`)
}
I'm not 100% sure about this being perfect but it should definitely point you in the right direction. The AVG() function calls might be unnecessary.
SELECT
Name,
SecondName,
SUM(fee.HoursWorked) as HoursWorked,
SUM(fee.fee) as fee,
YEAR(AVG(fee.Date)) as year,
MONTH(AVG(fee.Date)) as month
FROM Staff
JOIN fee ON staff.id = fee.staffid
ORDER BY fee.Date
GROUP BY staff.id, YEAR(fee.Date), MONTH(fee.Date)