How to display tree results count by each month? - mysql

I am trying to count achieve 3 results in one query:
Count all results where ‘app_creationdate’ = ('month') from current row
Count all results where ‘app_start’ = ('month') from current row
Count all results where ‘app_creationsdate’ < ‘app_start’ and ‘app_start’ = ('month') from current row
My Table:
app_id | app_creationdate(timestamp) | app_start(datetime)
00001 | 2014-11-17 19:39:04 | 2014-11-18 09:30:00
SELECT
DATE_FORMAT( app_creationsdate, '%m' ) AS 'month',
COUNT( app_id ) AS 'new',
(SELECT COUNT( app_id )
FROM appointments WHERE MONTH(app_start) = MONTH(NOW())) AS 'act',
(SELECT COUNT( app_id )
FROM appointments WHERE MONTH(app_creationsdate) < MONTH(app_start)) AS 'prev'
FROM appointments
WHERE app_owner = 2 AND app_creationsdate > DATE_SUB(now(), INTERVAL 12 MONTH)
GROUP BY DATE_FORMAT( app_creationsdate, '%Y%m' )

This may be closer to what you want. I'm still a bit confused about the prev scenario, so I did my best. I use EXTRACT(YEAR_MONTH FROM ...) to get the year and month, without the day, of each date so that we can do monthly comparisons. That's probably what you were trying to do with the DATE_FORMAT business.
SELECT DATE_FORMAT( app_creationsdate, '%m' ) AS 'month',
COUNT( app_id ) AS 'new',
-- get all other appointments that start in this month
(SELECT COUNT( act.app_id )
FROM appointments AS act
WHERE EXTRACT(YEAR_MONTH FROM act.app_start) = EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)) AS 'act',
-- get all appointments that were created before they started (???) and that started before this month
(SELECT COUNT( prev.app_id )
FROM appointments AS prev
WHERE EXTRACT(YEAR_MONTH FROM prev.app_creationsdate) < EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)
AND EXTRACT(YEAR_MONTH FROM prev.app_start) = EXTRACT(YEAR_MONTH FROM appointments.app_creationsdate)) AS 'prev'
FROM appointments
WHERE app_owner = 2
AND app_creationsdate > DATE_SUB(now(), INTERVAL 12 MONTH)
GROUP BY EXTRACT(YEAR_MONTH FROM app_creationsdate)

I am not entirely sure what you are trying to accomplish but I do notice one thing:
DATE_FORMAT(a2.app_start, '%m' ) = DATE_FORMAT('month', '%m' )
This: DATE_FORMAT('month', '%m' )...evaluates to NULL so equating that with anything is never going to work (I don't think anyway, but I'm new to MySQL... :) ).

Related

Retrieve data for specific months

MySQL Query is like this
SELECT MONTHNAME(access_date) as date,
DATE_FORMAT( access_date, '%m/%Y' ) as month_date ,
COUNT( log_id ) as total_count
FROM user_activity_log
WHERE dam_id = (
SELECT dam_id
FROM dam_content_details
WHERE content_type= '$content_type'
)
AND access_date >= last_day(NOW() - INTERVAL ($month) MONTH)
GROUP BY MONTH( access_date )
ORDER BY access_date ASC
i will pass the numbers like 1,2,3.... then its giving value for that month.
The problem i faced is it retrieving the data per 30 days,60 days like that. I want if i will write $month = '1; then it should return the current month data & previous month data starting from day 1.
My sample output - $month = 2
date month_date total_count
--------- ------------ -----------
December 12/2013 4
January 01/2014 1
I want for december it should calculate from 12/01/2013. 1st December 2013. Any idea how to solve it ?
You just have to remove = from >=.
Try this:
SELECT MONTHNAME(access_date) as date,
DATE_FORMAT( access_date, '%m/%Y' ) as month_date ,
COUNT( log_id ) as total_count
FROM user_activity_log
WHERE dam_id = (SELECT dam_id FROM dam_content_details WHERE content_type= '$content_type') AND
access_date > LAST_DAY(NOW() - INTERVAL (($month)+1) MONTH)
GROUP BY MONTH( access_date )
ORDER BY access_date ASC

Fetch data from last day, week, month and year in Mysql

I read many topics to fetch data that posted in different periods, but as the Time in my mysql table is in STRING format I couldn't make it happen.
SELECT s.user_id, count(*) AS wins, u.username, u.avatar,u.avatar_uploaded
FROM on_scores AS s
LEFT JOIN on_users AS u ON (u.userid = s.user_id)
WHERE s.is_high = '1' AND DATE(s.date_score) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY s.user_id
ORDER BY wins DESC
LIMIT 10
I tried the STR_TO_DATE method but still no output.
Use the from_unixtime function to get the time into a date-like format.
More info here.
Information on formatting the resultant date - here.
Example:
select date_sub( from_unixtime( s.datescore ), INTERVAL 1 MONTH ) as monthfromdatevalue;
select datediff( from_unixtime( s.datescore, curdate()) as howlongago_fromtoday;

MySQL Count IF and JOIN

I have two tables:
deskcases: | CaseID | Resolved At(Date) | Labels |
ringcentral: | Date | Type | Action Result |
My goal is to have the following output for the previous 7 days :
| Date | Count of TotalResolvedCases | Count of Total Calls |
I need to count the cases and calls in two separate tables then join and group the counts by the date. I'm also dealing with differing date formatting in the two tables, hence the wacky group by and join functions.
I also need to to have the join include all dates in the previous 7 days (deskcases has all dates so an INNER JOIN should work here I thought?)
To close, I've tried to run the following query below and it just churns with no result after a minute or two. Any idea on how to get this working? Thank you in advance for your help! :-)
(Running MySQL 5.0.96)
SELECT
DATE_FORMAT(
deskcases.`Resolved At`,
'%Y-%m-%d'
)AS Date1,
(
SELECT
COUNT(deskcases.`Case #`)
FROM
deskcases
WHERE
deskcases.Labels NOT LIKE '%SPAM%'
AND deskcases.Labels NOT LIKE '%Online Orders%'
AND deskcases.Labels NOT LIKE '%Internal SPAM%'
AND deskcases.`Resolved At` > NOW()- INTERVAL 8 DAY
)AS TotalResolvedCases,
(
SELECT
COUNT(ringcentral.Counter)
FROM
ringcentral
WHERE
`ringcentral`.`Type` = 'Voice'
AND `Action Result` = 'Accepted'
AND ringcentral.`Date` > NOW()- INTERVAL 8 DAY
)AS TotalCalls
FROM
deskcases
INNER JOIN ringcentral ON DATE_FORMAT(
deskcases.`Resolved At`,
'%Y-%m-%d'
)= ringcentral.Date
GROUP BY
Date1
ORDER BY
Date1 ASC
EDIT
I was able to edit this slightly to give me some result but it seems like I am counting ALL cases and calls with my sub-select queries and the totals are not being grouped by date. Here is the code:
SELECT
DATE_FORMAT(
deskcases.`Resolved At`,
'%Y-%m-%d'
)AS Date1,
(
SELECT
COUNT(deskcases.`Case #`)
FROM
deskcases
WHERE
deskcases.Labels NOT LIKE '%SPAM%'
AND deskcases.Labels NOT LIKE '%Online Orders%'
AND deskcases.`Case Status` LIKE '%Resolved%'
)AS TotalResolvedCases,
(
SELECT
COUNT(ringcentral.Counter)
FROM
ringcentral
WHERE
`ringcentral`.`Type` = 'Voice'
AND `Action Result` = 'Accepted'
)AS TotalCalls
FROM
deskcases
LEFT OUTER JOIN ringcentral ON DATE_FORMAT(
deskcases.`Resolved At`,
'%Y-%m-%d'
)= ringcentral.Date
WHERE deskcases.`Resolved At` > NOW()- INTERVAL 8 DAY
GROUP BY
Date1
ORDER BY
Date1 ASC
In this case you should definitely not join on date.
For example you may have this data:
deskcases ringcentral
--------- -----------
date | whatever_d date | whatever_r
---------------------- ----------------------
today x yesterday u
yesterday y
yesterday z
Now, when you join them you'll get this:
joinedTable
-----------
date | whatever_d | whatever_r
-------------------------------------
today x
yesterday y u
yesterday z u
Oops, you got 2 times an entry from ringtones table, but you wanted just 1.
So, how do you get your data? Either write 2 statements or combine them with UNION:
SELECT
DATE(`Resolved At`) AS Date1,
"Deskcases" AS fromTable,
COUNT(*) AS TotalNumber
FROM
deskcases
WHERE
deskcases.Labels NOT LIKE '%SPAM%'
AND deskcases.Labels NOT LIKE '%Online Orders%'
AND deskcases.Labels NOT LIKE '%Internal SPAM%'
AND deskcases.`Resolved At` > CURDATE()- INTERVAL 8 DAY
GROUP BY 1, 2
UNION ALL
SELECT
`Date` AS Date1,
"ringcentral" AS fromTable,
COUNT(*) AS TotalNumber
FROM
ringcentral
WHERE
`ringcentral`.`Type` = 'Voice'
AND `Action Result` = 'Accepted'
AND ringcentral.`Date` > CURDATE()- INTERVAL 8 DAY
GROUP BY 1, 2
Also note, that I changed NOW() to CURDATE(). In deskcases table your date column seems to be a timestamp. When you subtract 8 days from '2013-03-20 10:06:00' you'll get '2013-03-12 10:06:00' and therefore you'll be missing all rows between '2013-03-12 00:00:00' and '2013-03-12 10:05:59'. Also I just used the DATE() function instead of DATE_FORMAT(). DATE_FORMAT() is a really nice and useful function in many ways, but in this case you have to type less characters when using DATE() :)
UPDATE:
SELECT
Date1,
SUM(CASE WHEN fromTable = 'Deskcases' THEN TotalNumber ELSE 0 END) AS TotalDeskcases,
SUM(CASE WHEN fromTable = 'ringcentral' THEN TotalNumber ELSE 0 END) AS TotalRingcentral
FROM (
SELECT
DATE(`Resolved At`) AS Date1,
'Deskcases' AS fromTable,
COUNT(*) AS TotalNumber
FROM
deskcases
WHERE
deskcases.Labels NOT LIKE '%SPAM%'
AND deskcases.Labels NOT LIKE '%Online Orders%'
AND deskcases.Labels NOT LIKE '%Internal SPAM%'
AND deskcases.`Resolved At` > CURDATE()- INTERVAL 8 DAY
GROUP BY 1, 2
UNION ALL
SELECT
`Date` AS Date1,
'ringcentral' AS fromTable,
COUNT(*) AS TotalNumber
FROM
ringcentral
WHERE
`ringcentral`.`Type` = 'Voice'
AND `Action Result` = 'Accepted'
AND ringcentral.`Date` > CURDATE()- INTERVAL 8 DAY
GROUP BY 1, 2
) sq
GROUP BY Date1

mysql get sum of hours / minutes / seconds

I have a table with: userid and timestamp each time a user opens a page a new field is inserted.
I am trying to get the total amount of hours / minutes / days / weeks that appear in a 1 month interval for multiple users.
I have tried a bunch of different queries but each have ended up terribly inefficient.
Ideally I'd like to end up with something like:
userid | minutes | hours | days | weeks
1 10080 168 7 1
2 1440 24 1 0
Hopefully someone can shed some light on how to do this.
Below is a query that I tried:
SELECT
w.time AS `week`,
d.time AS `day`,
h.time AS `hour`,
m.time AS `minutes`
FROM (
SELECT
SUM( t.time ) AS `time`
FROM (
SELECT
COUNT( DISTINCT WEEK( `timestamp` ) ) AS `time`
FROM table
WHERE
userid = "1"
AND
`timestamp` > DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
GROUP BY MONTH( `timestamp` )
) t
) w,
(
SELECT
SUM( t.time ) AS `time`
FROM (
SELECT
COUNT( DISTINCT DAY( `timestamp` ) ) AS `time`
FROM table
WHERE
userid = "52"
AND
`timestamp` > DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
GROUP BY MONTH( `timestamp` )
) t
) d,
(
SELECT
SUM( t.timestamp ) AS `time`
FROM (
SELECT
COUNT( DISTINCT HOUR( `timestamp` ) ) AS `time`
FROM table
WHERE
userid = "1"
AND
`timestamp` > DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
GROUP BY DAY( `timestamp` )
) t
) h,
(
SELECT
SUM( t.timestamp ) AS `time`
FROM (
SELECT
COUNT( DISTINCT MINUTE( `timestamp` ) ) AS `time`
FROM table
WHERE
userid = "1"
AND
`timestamp` > DATE_SUB( NOW( ) , INTERVAL 1 MONTH )
GROUP BY HOUR( `timestamp` )
) t
) m
It seems awfully excessive for this task, maybe someone has something better?
It's not clear to me what you want to "total".
If you want to determine whether a user had a "hit" (or whatever transaction it is you are storing in the table) at any given minute within the month), and then you want to count the number of "minute periods" within a month that a user had a hit:
SELECT t.userid
, COUNT(DISTINCT DATE_FORMAT(t.timestamp,'%Y-%m-%d %H:%i')) AS minutes
, COUNT(DISTINCT DATE_FORMAT(t.timestamp,'%Y-%m-%d %H' )) AS hours
, COUNT(DISTINCT DATE_FORMAT(t.timestamp,'%Y-%m-%d' )) AS days
, COUNT(DISTINCT DATE_FORMAT(t.timestamp,'%X-%V' )) AS weeks
FROM mytable t
WHERE t.timestamp >= '2012-06-01'
AND t.timestamp < '2012=07-01'
GROUP BY t.userid
What this is doing is taking each timestamp, and putting it into a "bucket", by chopping off the seconds, chopping off the minutes, chopping off the time, etc.
Basically, we're taking a timestamp (e.g. '2012-07-25 23:15:30') and assigning it to
minute '2012-07-25 23:15'
hour '2012-07-25 23'
day '2012-07-25'
A timestamp of '2012-07-25 23:25:00' would get assigned to
minute '2012-07-25 23:25'
hour '2012-07-25 23'
day '2012-07-25'
Then we go through and count the number of distinct buckets we assigned a timestamp to. If that's all the hits for this user in the month, the query would return a 2 for minutes, and a 1 for all other period counts.
For a user with a single hit within the month, all the counts for that user will be a 1.
For a user that has all their "hits" within exactly the same minute, the query will again return a 1 for all the counts.
(For a user with no "hits" within a month, no row will be returned. (You'd need to join another row source to get a list of users, if you wanted to return zero counts.)
For a user with a "hit" every second within a single day, this query will return counts like that shown for userid 2 in your example.
This result set gives you a kind of an indication of a user's activity for a month... how many "minute periods" within a month the user was active.
The largest value that could be returned for "days" would be the number of days in the month. The largest possible value to be returned for "hours" would be 24 times the number of days in the month times. The largest possible value returned for "minutes" would be 1440 times the number of days in the month.
But again, it's not entirely clear to me what result set you want to return. But this seems like a much more reasonable result set than the one from the previously "selected" answer.
SELECT userid, SUM(MINUTE(timestamp)) AS minutes, SUM(MINUTE(timestamp))/60 AS hours, SUM(MINUTE(timestamp))/(60*24) AS days, SUM(MINUTE(timestamp))/(60*24*7) AS weeks
FROM Table
GROUP BY userid
If neccesary, use ROUND(SUM(MINUTE(timestamp)), 0) if you want integer numbers.

MYSQL Query group by custom Month date?

I wrote a query that returns monthly sales.
SELECT
count(O.orderid) as Number_of_Orders,
concat (MonthName(FROM_UNIXTIME(O.`date`)),' - ',year(FROM_UNIXTIME(O.date))) as Ordered_Month,
sum(O.total) as TotalAmount,
Month(FROM_UNIXTIME(O.`date`)) as Month_of_Year,
year(FROM_UNIXTIME(O.date)) as Sale_Year
FROM orders O
group by Month_of_Year, Sale_Year
order by Sale_Year DESC,Month_of_Year DESC
I would like to make it group for a custom date like
instead of 1st to 1st, it should group for 10th -10th of every month.
Not sure how to group it that way!
because you are dealing with a time "shift", you'll have to do that math in your equation to "fake it out". Something like
SELECT
count(O.orderid) as Number_of_Orders,
concat(
MonthName( Date_Sub( FROM_UNIXTIME(O.`date`), INTERVAL 10 DAY )),
' - ',
Year( Date_Sub( FROM_UNIXTIME(O.date), INTERVAL 10 DAY) )
) as Ordered_Month,
sum(O.total) as TotalAmount,
Month( Date_Sub( FROM_UNIXTIME(O.`date`), INTERVAL 10 DAY )) as Month_of_Year,
Year( Date_Sub( FROM_UNIXTIME(O.date), INTERVAL 10 DAY )) as Sale_Year
FROM
orders O
group by
Month_of_Year,
Sale_Year
order by
Sale_Year DESC,
Month_of_Year DESC
So, in essence, you are taking the dates ex: March 11-31 + April 1-10 and subtracting "10 days" from them... so for the query, they will look like March 1-31, and April 11-30 will appear like April 1-20 + May, etc for rest of each year...
Not tested.
group by Month_of_Year, ceil(day(o.`date`)/10), Sale_Year
This is a better idea in order to avoid having 4 groups but just 3
select
month(my_date) as your_month,
year(my_date) as your_year,
case
when day(my_date) <= 10 then 1
when day(my_date) between 11 and 20 then 2
else 3 end as decade,
count(*) as total
from table
group by
your_month,your_year,decade
Adapt it to your needs.