Mysql query to count result by removing time from datetime - mysql

I am trying to write one query in which i need to fetch/count records which are registered on same date. But the issue is that in mysql structure created_date field have "datetime" structure.
Let me give you example
If 5 people are registered on 2015-02-25 and 6 people registered on 2015-02-11. It will output as
Sno. Date. count
1) 2015-02-25 5
2) 2015-02-11 6
Here is sample of attached database rows for better understanding
http://i.stack.imgur.com/iPeLl.png

SELECT date(created_at),count(*) FROM myTable GROUP BY date(created_at)

It might be the one that you expected.
SELECT
DATE_FORMAT(created_at,"%Y-%m-%d") AS Date,
COUNT(*) AS count
FROM table_name
GROUP BY DATE_FORMAT(created_at,"%Y-%m-%d")
ORDER BY created_at DESC;
This query will count the registered people in each day. Of course the latest registration will come first.

your query should be like this:
select date(created_at) created_at, count(*) from TABLE
group by date(created_at)
Select between dates
select date(created_at) created_at, count(*) from TABLE
where date(created_at) >= '2015-02-11' and date(created_at) <= '2015-02-25'
group by date(created_at)
With between:
select date(created_at) created_at, count(*) from Mytable
where date(created_at) BETWEEN '2015-01-05' AND '2015-02-25'
group by date(created_at)
Referrence: count()

Related

MySQL: Multiple SELECT Statements in one Query

Im still learning MySQL however I would like to know how to query multiple SELECT statements in one query.
Currently I have two queries, one that displays Order count for 12 months and another for one month. I would like to query both at the same time however receive two different results.
I have tried using UNION with my query however it only outputs into one table and its quite hard to differentiate the result with what query.
SQL:
SELECT OrderDate, OrderItems, COUNT(*) AS Total FROM tb_orders WHERE OrderDate > DATE_SUB(now(), INTERVAL 12 MONTH) GROUP BY OrderItems ORDER BY Total DESC LIMIT 10
SELECT OrderDate, OrderItems, COUNT(*) AS Total FROM tb_orders WHERE OrderDate > DATE_SUB(now(), INTERVAL 1 MONTH) GROUP BY OrderItems ORDER BY Total DESC LIMIT 10;
TIA
You can merge the 2 queries by creating an identifier on the fly whether the record is from the monthly or yearly query. Column type is a column for this purpose in below query,
SELECT z.*
FROM
(
SELECT OrderDate, OrderItems, COUNT(*) AS Total, 'YEAR' as type
FROM tb_orders
WHERE OrderDate > DATE_SUB(now(), INTERVAL 12 MONTH)
GROUP BY OrderItems
LIMIT 10
UNION
SELECT OrderDate, OrderItems, COUNT(*) AS Total, 'MONTH' as type
FROM tb_orders
WHERE OrderDate > DATE_SUB(now(), INTERVAL 1 MONTH)
GROUP BY OrderItems
LIMIT 10
) AS z
ORDER BY z.Total DESC;
Working Fiddle
With union, you can always add hard-coded values to help differentiate rows:
select 'Invertebrate' as AnimalPhylum, species as AnimalSpecies from invertebrates_table
union
select 'Vertebrate', species from vertebrates_table;

Avg function not returning proper value

I expect this query to give me the avg value from daily active users up to date and grouped by month (from Oct to December). But the result is 164K aprox when it should be 128K. Why avg is not working? Avg should be SUM of values / number of current month days up to today.
SELECT sq.month_year AS 'month_year', AVG(number)
FROM
(
SELECT CONCAT(MONTHNAME(date), "-", YEAR(DATE)) AS 'month_year', count(distinct id_user) AS number
FROM table1
WHERE date between '2020-10-01' and '2020-12-31 23:59:59'
GROUP BY EXTRACT(year_month FROM date)
) sq
GROUP BY 1
Ok guys thanks for your help. The problem was that on the subquery I was pulling the info by month and not by day. So I should pull the info by day there and group by month in the outer query. This finally worked:
SELECT sq.day_month, AVG(number)
FROM (SELECT date(date) AS day_month,
count(distinct id_user) AS number
FROM table_1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY 1
) sq
GROUP BY EXTRACT(year_month FROM day_month)
Do not use single quotes for column aliases!
SELECT sq.month_year, AVG(number)
FROM (SELECT CONCAT(MONTHNAME(date), '-', YEAR(DATE)) AS month_year,
count(distinct id_user) AS number
FROM table1
WHERE date >= '2020-10-01' AND
date < '2021-01-01'
GROUP BY month_year
) sq
GROUP BY 1;
Note the fixes to the query:
The GROUP BY uses the same columns as the SELECT. Your query should return an error (although it works in older versions of MySQL).
The date comparisons have been simplified.
No single quotes on column aliases.
Note that the outer query is not needed. I assume it is there just to illustrate the issue you are having.

How to count a field per day and then GROUP BY YEARWEEK

If i have a database with 2 columns, date and account and i want to first count account per day and then group by week. How wrong is my code and how to do it?
I edited my code a little bit, i was not thinking right from the beginning. I want the sum to be 9 for week 48.
SELECT date, account,
(SELECT date, COUNT(DISTINCT account)
FROM t1
GROUP BY date
) AS sum
FROM t1
GROUP BY YEARWEEK(date)
You seem to be looking for a simple aggregate query with count(distinct ...):
select yearweek(date) year_week, count(distinct account) cnt_account
from t1
group by yearweek(date)
order by year_week
Note: yearweek() gives you the year and week; this is better than week(), if your data spreads over several years.
EDIT
From the comments, you need two levels of aggregation:
select yearweek(dy) year_week, sum(cnt) cnt_account
from (
select date(t1.date) dy, count(distinct t1.account) cnt
from t1
group by date(t1.date)
) t
group by yearweek(dy)
order by year_week

Group data by Year and Month

I have a table with 4 columns:
1. customerID
2. dateAdded
3. productID
4. quantity
The format of dateAdded is like this: 20180730 (YearMonthDay).
I want to group the rows in the table by year and month.
I tried the code below but it doesn't work. I still see rows with the same year and month repeated, but different day.
SELECT dateAdded
, SUM(quantity)
FROM testTable
GROUP
BY DATE_FORMAT(dateAdded, '%Y%m')
, dateAdded
ORDER
BY dateAdded DESC
Any idea how to fix this?
Thank you
Do not group by what you do not want the data to be grouped. Since you provide dateAdded as a parameter to be grouped with, it splits the data by dateAdded and you gain nothing out of year-month grouping. Remove the columns from select/groupby that you use for grouping like this:
SELECT DATE_FORMAT(dateAdded, '%Y%m')
, SUM(quantity)
FROM testTable
GROUP BY
DATE_FORMAT(dateAdded, '%Y%m')
If you store dateAdded as 20180730, looks like it's a string, so it wont work with DATE_FORMAT function, you can use SUBSTRING instead
something like
SELECT dateAdded, SUM(quantity), SUBSTRING(dateAdded, 1, 6) as d
FROM testTable
GROUP BY d
ORDER BY dateAdded DESC
use year and month function
SELECT Year(dateAdded) as YearOfDate,Month(dateAdded) as MonthOfdate,
, SUM(quantity) as Qty
FROM testTable
GROUP
BY Year(dateAdded), Month(dateAdded)
ORDER BY dateAdded DESC

How to count rows in db for each hour?

In table are two columns: Datestamp like 2012-12-16 with type date and Timestamp like 12:22:59 with type time. Is it possible to get count of rows for each hour for specific day with 1 sql? On return i need to get 24 numbers.
Something like this:
SELECT COUNT(*) FROM your_table
WHERE `Datestamp` = '2012-12-16'
GROUP BY HOUR(`Timestamp`)
SELECT datestamp as day, hour(timestamp) as hour, count(*)
FROM your_table
GROUP BY datestamp, hour(timestamp)