SQL: how to get sum() of counted values [duplicate] - mysql

This question already has answers here:
Calculate a running total in MySQL
(5 answers)
Closed 8 years ago.
I'm using the following statement to read out user-registrations
SELECT DAY(p.creationInstant) as day, MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year, count(p.id) as users
FROM person p WHERE p.enrollmentStatus ="Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day
This will give me the following output:
day month year users
1 1 2013 3
2 1 2013 5
3 1 2013 7
...
Now I'd like to have a 4th column that sums up the users:
day month year users **totalUsers**
1 1 2013 3 3
2 1 2013 5 8
3 1 2013 7 15
...
But somehow I can't figure it out how to do it with SQL (dbms: mySQL).

So that's how my statement looks after the hint to the 'running totals' question and it works like a charm:
SET #runtot:=0;
SELECT q1.day, q1.month, q1.year, q1.users,
(#runtot := #runtot + q1.users) AS totalUsers
FROM (
SELECT DAY(p.creationInstant) as day, MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year, count(p.id) as users
FROM PERSON p where p.enrollmentStatus ="Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day) as q1

select day,
month,
year,
(SELECT sum(a.id)
FROM person a
WHERE a.enrollmentStatus = "Enrolled"
and DAY(a.creationInstant) <= b.day)
from (SELECT DAY(p.creationInstant) as day,
MONTH(p.creationInstant) as month,
YEAR(p.creationInstant) as year,
count(p.id) as users
FROM person p
WHERE p.enrollmentStatus = "Enrolled"
GROUP BY year, month, day
ORDER BY year, month, day) b

Related

how to get pending months from due entries using mysql

I have the entries of monthly dues like,
Table name : month_dues,
Columns:
customer_id,
due_date,
due_amount
These table have lot of due entries.
customer_id due_date due_amount
--------------------------------------
1 2018-12-01 100
1 2019-01-01 100
1 2019-02-01 100
1 2019-10-01 100
so, how to select pending due months from these record?
in my table customer 1 not paid dues for these months,
2019-03,2019-04,2019-05,2019-06,2019-07,2019-08, 2019-09
customer pay the due every month so
For select paid dues from table using,
SELECT customer_id, due_date, due_amount FROM month_dues where customer_id='1' where due_date>='2019-01-01' and due_date<='2019-10-18';
How to get pending due month and year using this table?
Which means, find month and year not in this record.
IF you are searching between the two dates
YOu can use this
select * from month_dues
where due_date between '2012-03-11 00:00:00' and '2012-05-11
23:59:00' && customer_id='1'
order by month_dues desc;
If you want to search the date(due_date) lower than today
SELECT * FROM month_dues WHERE due_date < CURDATE();
And you are refeering to the record that is not belong to the query you can find some NOT IN query
Like
`SELECT * FROM month_dues NOT IN ( select * from month_dues
where due_date between '2012-03-11 00:00:00' and '2012-05-11
23:59:00' && customer_id='1'
order by month_dues desc;
)`
So basically you need to validate your table against some kind of calendar, here is a simple solution that only works for the current year, maybe you can use it as a start or someone else could improve it
SELECT m.MONTH
FROM (SELECT 1 AS MONTH
UNION SELECT 2 AS MONTH
UNION SELECT 3 AS MONTH
UNION SELECT 4 AS MONTH
UNION SELECT 5 AS MONTH
UNION SELECT 6 AS MONTH
UNION SELECT 7 AS MONTH
UNION SELECT 8 AS MONTH
UNION SELECT 9 AS MONTH
UNION SELECT 10 AS MONTH
UNION SELECT 11 AS MONTH
UNION SELECT 12 AS MONTH) as m
WHERE m.MONTH NOT IN (SELECT MONTH(due_date)
FROM due_months
WHERE customer_id = 1
AND YEAR(due_date) = YEAR(CURDATE()))
AND m.MONTH < MONTH(CURDATE()) -- needs to be improved as well

How to get the counts of last 3 months with month names, if no record for that month need to get 0 with month name [duplicate]

This question already has answers here:
MySQL monthly Sale of last 12 months including months with no Sale
(3 answers)
Get Record Per Month But Also Get Zero If No Records That Month
(2 answers)
Mysql to select month-wise record even if data not exist
(2 answers)
MySQL query to get last 12 months data grouped by month including zero counts
(1 answer)
Closed 4 years ago.
I want get the last 3 months data from current date then i will get four month names in that i have only 3 month data but i do not have one month data in middle.
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name
FROM patient_status as p, visit_history_details as v
WHERE v.visit_id = p.visit_id and v.hospital_code = 'id'
and p.doctor_id = '2' and v.updated >= now()-interval 3 month
GROUP by Month_name
My Result are coming like this:
January 10
December 12
October 10
But I want this result:
January 10
December 12
November 0
October 10
please help me how to solve this issue
For the month you should use a subquery for get all the month you need:
select monthname(my_date), ifnull(count, 0)
from (
select str_to_date('2018-01-01', '%Y-%m-%d') as my_date
union
select str_to_date('2018-10-01', '%Y-%m-%d')
union
select str_to_date('2018-11-01', '%Y-%m-%d')
union
select str_to_date('2018-12-01', '%Y-%m-%d')
) t
left join (
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name,
MONTH(v.updated) as my_month
FROM patient_status as p
INNER JOIN visit_history_details as v
ON v.visit_id = p.visit_id
WHERE v.hospital_code = 'id'
and p.doctor_id = '2'
and v.updated >= now()-interval 3 month
GROUP by Month_name
) r on r.my_month = t.my_month
And you should avoid old implicit join syntax and use the explicit syntax.
Or as suggested by Salman A for a more general solution:
select monthname(my_date), ifnull(count, 0)
from (
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 1 MONTH as my_date
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 2 MONTH
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 3 MONTH
union
select LAST_DAY(CURRENT_TIMESTAMP) + INTERVAL 1 DAY - INTERVAL 4 MONTH
) t
left join (
SELECT
count(v.visit_id) as count,
MONTHNAME(v.updated) AS Month_name,
MONTH(v.updated) as my_month
FROM patient_status as p
INNER JOIN visit_history_details as v
ON v.visit_id = p.visit_id
WHERE v.hospital_code = 'id'
and p.doctor_id = '2'
and v.updated >= now()-interval 3 month
WHERE v.visit_id = p.visit_id and v.hospital_code = 'id'
and p.doctor_id = '2' and v.updated >= now()-interval 3 month
GROUP by Month_name

Mysql count columns values based on condition

I have a table with columns day, month, year, total_payments. And I have to calculate total_payments according to days, months, years.
How can I calculate values?
I am thinking code like :
select
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
day;
select
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
month;
select
month, year, sum(total_payments)
from
webassignment.subscription_stats
group by
year;
but it will not return the correct answers. And I want to calculate total_payments daywise, monthwise, yearwise. Please help me to find values.
Sample input :
Day Month Year Total_payments
10 01 2008 10
10 01 2008 20
11 02 2008 10
10 03 2010 10
Output:
Daywise :
day month year total_payments
-----------------------------
10 01 2008 30
11 02 2008 10
10 03 2010 10
Same for month and yearwise
You can get a summary with Totals by Year, Month and Day using GROUP BY WITH ROLLUP:
SELECT
`Year`,
`Month`,
`Day`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day` WITH ROLLUP;
If you want individual queries for Year, Month and Day:
By Year:
SELECT
`Year`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`
ORDER BY `Year;
By Month:
SELECT
`Year`,
`Month`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
WHERE `Year` = 2017
GROUP BY `Year`,`Month`
ORDER BY `Year`,`Month`;
By Day:
SELECT
`Year`,
`Month`,
`Day`,
SUM(`Total_payments`) as `Totals`
FROM `webassignment`.`subscription_stats`
GROUP BY `Year`,`Month`,`Day`
ORDER BY `Year`,`Month`,`Day`;
A way could be the use on an union for show the different result based on different group by level
select day, month,year,sum(total_payments)
from webassignment.subscription_stats group by day, month,year
union
select null, month,year,sum(total_payments)
from webassignment.subscription_stats group by month,year
union
select null, null ,year,sum(total_payments)
from webassignment.subscription_stats group by year
order by year, month, day
for the sample you provided should be enough
select day, month,year,sum(total_payments)
from webassignment.subscription_stats group by day, month,year
order by day, month,year

mysql counts in a month and total counts upto month

I want the count of records in every month and total count of records from start upto that month.
For ex.,
I have a table that looks like this:
#id,created#
1,'2016-01-01'
2,'2011-02-02'
3,'2011-02-09'
4,'2011-02-05'
5,'2011-03-07'
6,'2011-03-08'
How do I select and group these so the output is:
#Month, new, total#
Jan 2016, 1, 1
Feb 2016, 3, 4
Mar 2016, 2, 6
Thanks very much.
Here you go:
SELECT DATE_FORMAT(`created`,'%M %Y') AS month, COUNT(*) AS count,
(SELECT count(*) FROM test WHERE MONTH(created) <= MONTH(t.created)) AS total
FROM test t
GROUP BY MONTH(created);
Here's the SQL Fiddle.
Using single table read:
SELECT
CONCAT(LEFT(MONTHNAME(dt), 3), ' ', YEAR(dt)) month,
new,
#total:=#total + new total
FROM
(SELECT
created - INTERVAL DAY(created) - 1 DAY dt, COUNT(*) new
FROM
t
GROUP BY created - INTERVAL DAY(created) - 1 DAY
ORDER BY dt) t
CROSS JOIN
(SELECT #total:=0) t2
Demo

Group mysql query by months or weeks with proper start/endings

I have searched and viewed a lot of answers on SO but even trying to apply all I found I get incorrect results.
I am trying to group my mysql results by week mon-sun, and by month from day 1 to last day of month
I have tried different types of grouping like:
GROUP BY YEARWEEK(data)
GROUP BY WEEK(data)
for weeks and
GROUP BY MONTH(data)
for months
all these grouping methods return uncorrect groupings. some results start in random days of the month or the week.
this is example query which get results from last month entries divided by week although the week grouping is not resulting in weeks from mon-sun.
SELECT *, count(id) AS count FROM leadz WHERE YEAR(data) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(data) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) GROUP BY YEARWEEK(data)
these are the week segments I get as results:
2016-07-01 2016-07-04 2016-07-16 2016-07-17 2016-07-25 2016-07-31
Next is a sample query of total entries grouped by month, again gropuing does not start from 1st of the month
SELECT *, count(id) AS count FROM leadz GROUP BY MONTH(data)
these are the month segments I get as result:
2016-04-18 2016-05-25 2016-06-01 2016-07-25 2016-08-02
Any help appreciated
For starting on monday you should use
YEARWEEK(data, 1)
or
WEEK(data,1)
see this for ref http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_week
so your select should be
SELECT *, count(id) AS count
FROM leadz
WHERE YEAR(data) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH)
AND MONTH(data) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH)
GROUP BY YEARWEEK(data, 1)