Mysql count query by Grouping Year and Month horizontal - mysql

I am new to mysql query and i am stuck on getting query. Basically, i want the date to group as Year and month (Jan'17, Feb'17...) in horizontal way (column) as shown in Image below.
Data are shown in image below:
Please help to create query.

You can do conditional aggregation - once per login_id and then overall and then union both the results.
Select login_idindex,
Sum(date_format(visitdate, '%Y%m') = '201701' ) as jan_17,
Sum(date_format(visitdate, '%Y%m') = '201702' ) as feb_17,
. . .,
Count(*) as total
From your_table
Where visitdate between ? and ?
Group by login_idindex
Union all
Select null,
Sum(date_format(visitdate, '%Y%m') = '201701' ) as jan_17,
Sum(date_format(visitdate, '%Y%m') = '201702' ) as feb_17,
. . .,
Count(*) as total
From your_table
Where visitdate between ? and ?;
Replace ? with actual dates or remove the where clause if you are working with all the dates.

Related

MySQL Query from version 5.1 is not working in 5.7

select * from batches join (
select * from (
select *, row_number() over (
partition by batch_id
order by date ASC
) as row_num
from batch_schedule where display = 'Yes'
) as d_schedule
where d_schedule.row_num = 1
)
as f_schedule
on batches.id = f_schedule.batch_id
WHERE (f_schedule.date BETWEEN '2021/03/01' AND '2021/04/30')
This query is working fine in version 5.1 but not working in 5.7
What I am trying to achieve is,
filtering batches based on batch_schedule start dates.
I need to select the 1st row from the right table with condition display = 'Yes' and order by date asc and based on that row value i need to display batches.
I am getting the below error message
select is not valid at this position for this server version expecting '(' with
select * from batches join ( SELECT * from batch_schedule
where display = 'Yes' group by batch_id order by date asc )
as f_schedule on batches.id = f_schedule.batch_id
where(f_schedule.date BETWEEN '2021/03/01' AND '2021/04/30');
I tried this and it works.
I am posting here in case if someone looking for the same thing it will help.

How to get total number of records sql daily

I am currently doing to get the count,
Select count(*) from MyTable WHERE ATTEMPT_DATE='01/JUNE/19';
Select count(*) from MyTable WHERE ATTEMPT_DATE='02/JUNE/19';
.
.
Select count(*) from MyTable WHERE ATTEMPT_DATE='30/JUNE/19';
Is there any way to get all the SUM of ( count(*) all dates)
You can use aggregation:
select ATTEMPT_DATE, count(*)
from MyTable
group by ATTEMPT_DATE;
If you want to counts dates within a range, use where:
select count(*)
from MyTable
where ATTEMPT_DATE in ('01/JUNE/19', . . . '30/JUNE/19');
You are using a non-standard date format. If this were a standard date format (or if the column really is a date/datetime value), then I would suggest inequalities rather than in.
Why don't you use direct count(*)
Select count(*) from MyTable WHERE ATTEMPT_DATE BETWEEN '01/JUNE/19' AND '30/JUNE/19'
for datewise count use group by
Select ATTEMPT_DATE, count(*) from MyTable
WHERE ATTEMPT_DATE BETWEEN '01/JUNE/19' AND '30/JUNE/19' group by ATTEMPT_DATE
Cheers!!

Pivot With Calendar Table

I am trying to pivot this data but I am getting an error of
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near ','.
Highlighting the comma after SUM([Total Count]) but it has to be there, what should I change so my query executes properly?
select *
FROM
(
select a.regionalLocale As [RL],
Count(ID) As [Total Count],
CONVERT(VARCHAR(20), dt.week) AS Week
FROM database14.dataTable a
INNER JOIN calendarDB.masterCalendar dt
ON a.SaleDate = dt.FullDate
WHERE a.SaleDate IS NOT NULL
) src
pivot
(
SUM([Total Count]), [RL]
For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv
You've got a few issues with your query.
One you've got the syntax SUM([Total Count]), [RL] in your PIVOT. You only want to include the column you are aggregating here.
Second, there is no need to use count(id) inside your subquery, let the PIVOT aggregation handle the total. Change your code to:
select [RL],
[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13]
FROM
(
select a.regionalLocale As [RL],
ID,
CONVERT(VARCHAR(20), dt.week) AS Week
FROM database14.dataTable a
INNER JOIN calendarDB.masterCalendar dt
ON a.SaleDate = dt.FullDate
WHERE a.SaleDate IS NOT NULL
) src
pivot
(
COUNT(ID)
For Week IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13])
) piv

SQL query that finds a negative change between two rows with the same name field

I have a single table with rows like this: (Date, Score, Name)
The Date field has two possible dates, and it's possible that a Name value will appear under only one date (if that name was recently added or removed).
I'm looking to get a table with rows like this: (Delta, Name), where delta is the score change for each name between the earlier and later dates. In addition, only a negative change interests me, so if Delta>=0, it shouldn't appear in the output table at all.
My main challenge for me is calculating the Delta field.
As stated in the title, it should be an SQL query.
Thanks in advance for any help!
I assumed that each name can have it's own start/end dates. It can be simplified significantly if there are only two possible dates for the entire table.
I tried this out in SQL Fiddle here
SELECT (score_end - score_start) delta, name_start
FROM
( SELECT date date_start, score score_start, name name_start
FROM t t
WHERE NOT EXISTS
( SELECT 1
FROM t x
WHERE x.date < t.date
AND x.name = t.name
)
) AS start_date_t
JOIN
( SELECT date date_end, score score_end, name name_end
FROM t t
WHERE NOT EXISTS
( SELECT 1
FROM t x
WHERE x.date > t.date
AND x.name = t.name
)
) end_date_t ON start_date_t.name_start = end_date_t.name_end
WHERE score_end-score_start < 0
lets say you have a table with date_value, sum_value
Then it should be something like that:
select t.date_value,sum_value,
sum_value - COALESCE((
select top 1 sum_value
from tmp_num
where date_value > t.date_value
order by date_value
),0) as sum_change
from tmp_num as t
order by t.date_value
The following uses a "trick" in MySQL that I don't really like using, because it turns the score into a string and then back into a number. But, it is an easy way to get what you want:
select t.name, (lastscore - firstscore) as diff
from (select t.name,
substring_index(group_concat(score order by date asc), ',', 1) as firstscore,
substring_index(group_concat(score order by date desc), ',', 1) as lastscore
from table t
group by t.name
) t
where lastscore - firstscore < 0;
If MySQL supported window functions, such tricks wouldn't be necessary.

SQL select aggregate values in columns

I have a table in this structure:
editor_id
rev_user
rev_year
rev_month
rev_page
edit_count
here is the sqlFiddle: http://sqlfiddle.com/#!2/8cbb1/1
I need to surface the 5 most active editors during March 2011 for example - i.e. for each rev_user - sum all of the edit_count for each rev_month and rev_year to all of the rev_pages.
Any suggestions how to do it?
UPDATE -
updated fiddle with demo data
You should be able to do it like this:
Select the total using SUM and GROUP BY, filtering by rev_year and rev_month
Order by the SUM in descending order
Limit the results to the top five items
Here is how:
SELECT * FROM (
SELECT rev_user, SUM(edit_count) AS total_edits
FROM edit_count_user_date
rev_year='2006' AND rev_month='09'
GROUP BY rev_user
) x
ORDER BY total_edits DESC
LIMIT 5
Demo on sqlfiddle.
Surely this is as straightforward as :
SELECT rev_user, SUM(edit_count) as TotalEdits
FROM edit_count_user_date
WHERE rev_month = 'March' and rev_year = '2014'
GROUP BY rev_user
ORDER BY TotalEdits DESC
LIMIT 5;
SqlFiddle here
May I also suggest using a more appropriate DATE type for the year and month storage?
Edit, re new Info
The below will return all edits for the given month for the 'highest' MonthTotal editor, and then re-group the totals by the rev_page.
SELECT e.rev_user, e.rev_page, SUM(e.edit_count) as TotalEdits
FROM edit_count_user_date e
INNER JOIN
(
SELECT rev_user, rev_year, rev_month, SUM(edit_count) AS MonthTotal
FROM edit_count_user_date
WHERE rev_month = '09' and rev_year = '2010'
GROUP BY rev_user, rev_year, rev_month
ORDER BY MonthTotal DESC
LIMIT 1
) as x
ON e.rev_user = x.rev_user AND e.rev_month = x.rev_month AND e.rev_year = x.rev_year
GROUP BY e.rev_user, e.rev_page;
SqlFiddle here - I've adjusted the data to make it more interesting.
However, if you need to do this across several months at a time, it will be more difficult given MySql's lack of partition by / analytical windowing functions.