I have a table with a list of tasks. Each task has a datetime field called "completedTime". Basically everytime a task is marked completed that field gets updated with the correct time.
Now I need to do a graph (using jQuery) for this result where the x axis is the months of the year (jan-dec) and the y axis is a number.
What is the sql query can I use so it would spit out 12 columns (Jan-Dec) with a number in each depending on how many tasks have a completedTime in that month.
I don't want to run the query below 12 times or each month.
SELECT * FROM `tasks` WHERE month(completedTime) between '02' and '03';
Any ideas?
If I understand correctly, your want it to return 12 rows (one for each month) with a count of the number of tasks.
If that is correct, then something like this should work. I added the year, which could be parametrized.
SELECT Count(*)
FROM Tasks
WHERE Year = 2011
GROUP BY Month(completedTime);
Revised with name for Month
SELECT Count(*) as total,
DateName(month, DateAdd(month, Month(completedTime), 0 ) - 1 ) as Month
FROM tasks
WHERE year(completedTime) = '2011'
GROUP BY Month(completedTime)
Related
Re-do Times 2 for clarity
For simplicity and clarity, the data I am aggregating is in a database I will refer to as "BaseA".
Normally, when comparing Month over month data, I can use the following query:
select date_trunc('month',hour) as date,
sum(a) as total_a,
sum(b) as available_b,
sum(c) as c,
sum(d) as net_d
from BaseA where id=12345 and hour >='2022-01-01'
group by date order by date desc
Instead of looking back and collecting ALL months from 2021-2022 for the duration I wish to view, I want to collect ONLY two months of data, those being the following:
October 2021
vs.
April 2022
I'd like the data to be visualized in the Month over month format, like so:
example
However, I would like to:
Select all BaseA columns (aka, select *)
Only include Two rows: April 2022 & October 2021
So, should come out like so:
example 2
This query is what Im trying to do (in word form since I can't write it)
Select *
from BaseA
where date
is in
April 2022
&
October 2022
The result of the above should result in 2 rows of data (one for each month referenced)
Is there a place in the below query where DISTINCT would make that actualized?
select * from BaseA
where id=12345 and
(
(month(month) = '04' and year(month) = '2022')
OR
(month(month) = '10' and year(month) = '2021')
)
--DISTINCT go where?
Appreciate the help!
To get data for the two months try something like this:
select * from BaseA
where _id=12345 and
(
(month(month) = '04' and year(month) = '2022')
OR
(month(month) = '10' and year(month) = '2021')
)
I have no idea what you mean by "return data consolidated (grouped) by month (so multiple lines occur per month)". Can you provide dummy data that illustrates the data that you have and the result that you want to achieve?
I am trying to fetch the count of records entered in each month of the financial year
For example, I have declared a column called issue in varchar because the data what I am taking is issues of the particular machine. And for example, let's say one issue is raised in July month I enter the data as 'Jul 19-1' and the again issue is raised in the month of September again I go back to the issue happened in July and enter the data as 'sep19-2'.
So in the backend, it takes as jul19-1 sep19-2
What can be the query that I can write for counting the number of issues raised in each month
I tried the below query but
SELECT COUNT(month_nc)
FROM `ncr`
WHERE month_nc='Jul18-1'
In some months there will be only one issue so I can the count of the month given in the above query
What will be the query if I want to fetch the count of each month
id issue issue_month
1 bearing jul18-1
sep18-2
2 motor jul18-2
3 battery apr18-3
ps: issue_month is declared in varchar(10)
Here are two methods. One using strings:
select left(issue_month, 5), count(*)
from t
group by left(issue_month, 5), count(*)
This will not order the values correctly.
You can convert to a date to order properly:
order by str_to_date(concat('01', left(issue_month, 5)), '%d%b%y')
Or, represent the dates correctly:
select str_to_date(concat('01', left(issue_month, 5)), '%d%b%y') as yyyymm, count(*)
from t
group by yyyymm
order by yyyymm;
Here is what you can do to split your issue_month into "month_year" and "issue_count"
yourTable
select id,
issue,
issue_month,
REGEXP_SUBSTR(issue_month, '[^-]+', 1) as month_year,
REGEXP_SUBSTR(issue_month, '[^-]+', 1,2 ) as issue_count
from yourTable;
Now you can aggregate the issue_count across issues or year_months or any other field in your table.
For example, to get the sum of all the issues for any given month_year
select
month_year,
sum(issue_count) issue_count
from
(select
id, issue, issue_month,
REGEXP_SUBSTR(issue_month, '[^-]+', 1) as month_year,
REGEXP_SUBSTR(issue_month, '[^-]+', 1,2 ) as issue_count
from yourTable) foo
group by month_year;
I am using the Graph Reports for the select below. The MySQL database only has the active records in the database, so if no records are in the database from X hours till Y hours that select does not return anything. So in my case, I need that select return Paypal zero values as well even the no activity was in the database. And I do not understand how to use the UNION function or re-create select in order to get the zero values if nothing was recorded in the database in time interval. Could you please help?
select STR_TO_DATE ( DATE_FORMAT(`acctstarttime`,'%y-%m-%d %H'),'%y-%m-%d %H')
as '#date', count(*) as `Active Paid Accounts`
from radacct_history where `paymentmethod` = 'PayPal'
group by DATE_FORMAT(`#date`,'%y-%m-%d %H')
When I run the select the output is:
Current Output
But I need if there are no values between 2016-07-27 07:00:00 and 2016-07-28 11:00:00, then in every hour it should show zero active accounts Like that:
Needed output with no values every hour
I have created such select below , but it not put to every hour the zero value like i need. showing the big gap between the 12 Sep and 13 Sep anyway, but there should be the zero values every hour
(select STR_TO_DATE ( DATE_FORMAT(acctstarttime,'%y-%m-%d %H'),'%y-%m-%d %H')
as '#date', count(paymentmethod) as Active Paid Accounts
from radacct_history where paymentmethod <> 'PayPal'
group by DATE_FORMAT(#date,'%y-%m-%d %H'))
union ALL
(select STR_TO_DATE ( DATE_FORMAT(acctstarttime,'%y-%m-%d %H'),'%y-%m-%d %H')
as '#date', 0 as Active Paid Accounts
from radacct_history where paymentmethod <> 'PayPal'
group by DATE_FORMAT(#date,'%y-%m-%d %H')) ;
I guess, you want to return 0 if there is no matching rows in MySQL. Here is an example:
(SELECT Col1,Col2,Col3 FROM ExampleTable WHERE ID='1234')
UNION (SELECT 'Def Val' AS Col1,'none' AS Col2,'' AS Col3) LIMIT 1;
Updated the post: You are trying to retrieve data that aren't present in the table, I guess in reference to the output provided. So in this case, you have to maintain a date table to show the date that aren't in the table. Please refer to this and it's little bit tricky - SQL query that returns all dates not used in a table
You need an artificial table with all necessary time intervals. E.g. if you need daily data create a table and add all day dates e.g. start from 1970 till 2100.
Then you can use the table and LEFT JOIN your radacct_history. So for each desired interval you will have group item (group by should be based on the intervals table.
I'm in need of some help structuring in-time queries. There's a few of them I need - but I think that if I can be shown how to do one, I can figure out the others.
What I'm after:
-Rolling 12 month view of 'inactive accounts'...ie number of accounts that have not placed an order in the 12 months prior.
-This ideally will be a subquery (in a much larger script) joining back on to a dates table (see below)
January 2015 | # of customers with no orders from 1/2014-1/2015
February 2015 | # of customers with no orders from 2/2014-2/2015
March 2015 | # of customers with no orders from 3/2014-3/2015
etc...
What I'm having trouble wrapping my mind around is how I'd structure a where clause to ensure that it scans all orders and only returns the total of account ID's that had not placed an order in the year prior to that month. I've used different combinations of DATEDIFF, DATESUB etc.
SELECT DATE_FORMAT(order_datetime, '%Y-%m'), COUNT DISTINCT (account_id)
FROM warehouse.orders
JOIN warehouse.accounts ON xyz
WHERE...
It feels like I'm on the right path - I just keep mentally going in circles trying to figure this out.
Cheers and thanks in advance.
I don't have enough reputation points to simply comment on your question. I don't fully understand it though.
Are you using SQLServer/TSQL or MySQL?
Do you want to have just one column which calculates the last 12 months' rolling average or 12 columns for the rolling average each month? If it is just one figures for the last 12 months tolling do you want that to be from the current day or the beginning of that month?
If it was SQL Server and a rolling 12 months to now, the calculation could be:
SELECT SUM(CASE WHEN DATEDIFF(y,GETDATE(),order_date_time) < 1 THEN COUNT(DISTINCT account_id) END) as January2015
If you're using MySQL replace GETDATE() with NOW()
If you want one value rolling but to the beginning of the month then you could use:
SELECT SUM(CASE WHEN DATEDIFF(y,DATEADD(M, DATEDIFF(M, 0, GETDATE()), 0),order_date_time) < 1 THEN COUNT(DISTINCT account_id) END) as January2015
If I've missed the point entirely, please let me know and I'll happily amend the answer
You should query between dates, in order to get the count of events for each id.
select case
when count(account_id)<0 then 'INACTIVE'
when count(account_id)>0 then 'ACTIVE'
from warehouse.orders
where data_format(order_datetime, '%m/%Y') between '1/2014' and '1/2015'
group by account_id)
I have a table titled "Reports" in MySQL that has a column titled "Flow_Total" which has a running total value that goes up every day and never resets, what i need is a query that takes the values that are stored in the "Flow_Total" column and divide them by month and tells me how much the value goes up every month.
This is how i would like to see the data:
https://skydrive.live.com/redir?resid=BC22A6E2F92CE833!11843&authkey=!ACgipFLKDJTBlN8
The value for the month is written on the last day of that month.
A summary of what i want to do is subtract the monthly change from the Flow_Total and display it in a separate column titled Monthly Total.
Maybe not the most pleasing SQL to the eyes, but this should do what you're asking; it'll just self join the table with itself delayed 1 month and calculate the difference from that.
SELECT DATE_FORMAT(MAX(a.`DATE`), '%b-%y') `DATE`,
MAX(a.`FLOW_TOTAL`) `Flow Total`,
(MAX(a.`FLOW_TOTAL`) - MAX(b.`FLOW_TOTAL`)) `Monthly Total`
FROM Reports a
LEFT JOIN Reports b
ON YEAR(a.`DATE`) = YEAR(DATE_ADD(b.`DATE`, INTERVAL 1 MONTH)) AND
MONTH(a.`DATE`) = MONTH(DATE_ADD(b.`DATE`, INTERVAL 1 MONTH))
GROUP BY YEAR(a.`DATE`), MONTH(a.`DATE`)
ORDER BY a.`DATE` DESC;
An SQLfiddle for testing.