I have an SQL database which is setted to full group on mode. My goal is to get the amount of rows (ID's) for every month. This is why I say Group By Datum. Because of the full group mode I cannot simply say Order By created_at. Because I have selected only %m.%Y. So I can only work with Datum which is cointaing my month and year.
I already tried to connect those values like CONCAT('DATE_FORMAT(created_at, '%Y-%m'), "-01 00:00:00") but also this isn't working... Even if I turn it into a UNIX Timestamp it isn't working: UNIX_TIMESTAMP(CONCAT('DATE_FORMAT(created_at, '%Y-%m'), "-01 00:00:00"))
I even tried this one:
Order By Year(DATE_FORMAT(created_at, '%Y')), Month DATE_FORMAT(created_at, '%m') But it isn't also working...
How can I sort my result by month and year without changing the Select values?
Sofar this is my actual SQL Query. Not working either.. I am nearly trying to find a solution since 1 hour...
SELECT COUNT(ID) AS Anzahl, DATE_FORMAT(created_at, '%m.%Y') AS Datum
FROM leads
WHERE created_at >= '2015-01-01' AND created_at <= '2018-01-01'
AND shopID = 4184
GROUP BY Datum
ORDER BY UNIX_TIMESTAMP(STR_TO_DATE(Datum, '%Y-%m-01 00:00:00'))
I would appreciate any kind of help! And no, I cannot change the Select values or turn off the full_group_mode.
The following will sort by year and then month in ascending order:
order by substring(datum,4,4), substring(datum,1,2)
sqlfiddle:http://sqlfiddle.com/#!9/16fab4/3
ORDER BY DATE_FORMAT(created_at, '%Y'), date_format(created_at, '%M') desc
This will sort the results by year ascending then by month descending.
Take a look at this SQL Fiddle to see the query using MySql 5.6
Related
Im trying to get the number of customers that a company had each day for the last 7 days. But when I run my code I get the total of customers for the week and is just displaying the last order date.
SELECT order_date, COUNT(DISTINCT buyerid) as 'customers' from orders
WHERE
date(order_date) >= curdate() - 7
AND date(order_date) <= curdate()
Your code is able to run because it's not in 'full group by only' mode. That is because you're not aggregating the order_date, so you end up displaying only the last date and counting all the buyerids. This is almost never an expected result, I might say.
I would rewrite it like so:
SELECT order_date, COUNT(DISTINCT buyerid) as 'customers'
FROM orders
WHERE
order_date >= date_sub(curdate(), interval 1 week)
GROUP BY order_date
Now it will count the distinct buyerids in each day.
Also, curdate() - 7 doesn't seem to work so I rewrote it entirely, assuming order_date is of date type.
Mind you might miss results if its a datetime, and in that case compare it to now() or strip time entirely.
I don't get the meaning of the line AND date(order_date) = curdate(). It seems to be right only if you want today's sales.
This is my SQL to fetch orders of current week:
SELECT * FROM orders
WHERE YEARWEEK(order_date, 1) = YEARWEEK(CURDATE(), 1)
ORDER BY order_date DESC;
But the problem is that it also selects records of future dates in the current week. How to stop that?
Just add a condition on the current date as well:
SELECT o.*
FROM orders o
WHERE YEARWEEK(order_date, 1) = YEARWEEK(CURDATE(), 1) AND
order_date <= CURDATE()
ORDER BY order_date DESC;
Be aware: if you use the order_date column in a function to build the where clause, this will result in a query which does not use an index on order_date and so should be avoided if your table can be big.
If you calculate the first date of the current week you can build your where clause just using order_date and it will use an index.
Maybe this can help to inspire you:
WHERE order_date BETWEEN DATEADD(DAY, -WEEKDAY(CURDATE())), CURDATE()) AND CURDATE()
I haven't tested this but adapted the function names to MySQL using the documentation. The idea is to calculate the first date of the current week so you know the range to filter.
i made a sql statement and looks fine i first wanted to show only weekly dates like this one
WHERE WEEK(date_add) = WEEK(UTC_TIMESTAMP())
this works fine outcome = '2017-02-27 12:08:24'
For MONTHS i change WEEK to MONTH or YEAR works great. But then someone asked me to show only the date like outcome = 'april' or 'juli' and then i was like how do i do that? so i searched on google and found out that i could use %M Month name (January..December)
I know i need
'%M'
but how can i have it work in my case.
I also did try
DATE_FORMAT(NOW(),'%M')
But the outome was 1
I did search other post before posting this one they did not help me.
SELECT
sum(totalExcl) AS total, saleType, date_add
FROM
ex.ps_ox_quo
WHERE
WEEK(date_add) = WEEK(UTC_TIMESTAMP())
AND saleType IN ('IEW')
GROUP BY date_add
ORDER BY date_add DESC
I think you just want date_format():
SELECT sum(totalExcl) AS total, saleType, date_add,
date_format(date_add, '%M')
FROM ex.ps_ox_quo
WHERE WEEK(date_add) = WEEK(UTC_TIMESTAMP()) AND
saleType IN ('IEW')
GROUP BY date_add, saleType
ORDER BY date_add DESC;
Note: You should probably include the year in the date comparison.
You have a datetime type for column date_add you can use MONTHNAME
SELECT
sum(totalExcl) AS total, saleType, MONTHNAME(date_add)
FROM
ex.ps_ox_quo
WHERE
WEEK(date_add) = WEEK(UTC_TIMESTAMP())
AND saleType IN ('IEW')
GROUP BY MONTHNAME(date_add)
ORDER BY MONTHNAME(date_add) DESC
try this
SELECT
sum(totalExcl) AS total, saleType, monthname(date_add)
FROM
ex.ps_ox_quo
WHERE
month(date_add) = month(UTC_TIMESTAMP())
AND saleType IN ('IEW')
GROUP BY month(date_add)
ORDER BY month(date_add) DESC
select YEAR_MONTH(now()) AS current_month
I have a query that's meant to return various statistics related to items released within some time period between yesterday and the first of the month last year. For the most part, the following query works as expected.
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, status B
WHERE A.ReleaseDate BETWEEN '2015-02-01' AND '2016-02-22'
AND A.ListID = B.ListID
GROUP BY MONTH(A.ReleaseDate)
ORDER BY FormattedReleaseDate DESC
This retrieves the specified statistics for every month between 2/1/15 and 2/22/16. However, it's not returning anything from this month. Just to check, I ran this exact same query, replacing the start date above with 2016-02-01, which retrieved the results I expected for just this month. Out of desperation I tried using a different column from item_info that serves the same purpose as status' TotalCost column, thereby alleviating the need for any sort of table join, but I'm still not getting the results from this month. I know it exists and falls within the date range. What exactly is wrong with my first query? I haven't specified a limit to the number of results.
First, you should:
group by FormattedReleaseDate
So if month is repeated in two different years shows as many rows as different pairs month-year are (and not stacking them together in one month, just giving you 12 rows as much).
You should try also:
WHERE STR_TO_DATE(A.ReleaseDate, '%Y-%m-%d')
between STR_TO_DATE('01/02/2015 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('22/02/2016 23:59:59', '%c/%e/%Y %H:%i:%s')
just to ensure your filter is more accurate.
So the entire query would be:
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, status B
WHERE
STR_TO_DATE(A.ReleaseDate, '%Y-%m-%d')
between STR_TO_DATE('01/02/2015 00:00:00', '%c/%e/%Y %H:%i:%s')
and STR_TO_DATE('22/02/2016 23:59:59', '%c/%e/%Y %H:%i:%s')
AND A.ListID = B.ListID
GROUP BY FormattedReleaseDate
ORDER BY FormattedReleaseDate DESC
I wasn't grouping the data properly.
SELECT DATE_FORMAT(A.ReleaseDate, '%Y-%m') AS FormattedReleaseDate, COUNT(*) AS ReleaseCount, SUM(A.SalesPrice)/COUNT(*) AS MAPAvg, SUM(B.TotalCost)/COUNT(*) AS COGSAvg
FROM item_info A, inventory_status B
WHERE A.ListID = B.ListID
AND A.ReleaseDate BETWEEN '$startDate' AND '$endDate'
AND A.HideInDealerPricelist = 0
GROUP BY YEAR(A.ReleaseDate), MONTH(A.ReleaseDate)
ORDER BY FormattedReleaseDate DESC
I have a CHANGES table with fields VALUE(integer) and CREATED_AT(timestamp). I want to know the total of the VALUE column grouped by each of the past 30 days (without making 30 queries).
So if yesterday there were records created with VALUEs of 10, -7, and 12; I would want a record returned with CREATED_AT = yesterday and TOTAL = 15.
Any help?
SELECT date(created_at) as CREATED_AT, sum(value) as TOTAL
FROM changes
WHERE created_at >= curdate() - interval 30 day
GROUP BY date(created_at);
Well, it slightly depends on what kind the timestamp is formatted in (SQL/ Unix/ etc). But this type of query might help you along:
SELECT
DATE_FORMAT(CREATED_AT, '%Y-%m-%d') ym,
COUNT(VALUE)
FROM foo
GROUP BY ym