Want all the latest visit of all the distinct user.
For this I am using below query
Event.order(time: :desc).select('DISTINCT ON(user_id) user_id, time')
Getting SQL syntax error.
ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC ' at line 1: SELECT DISTINCT ON(user_id) user_id, time FROM `events` ORDER BY `events`.`time` DESC LIMIT 11)
events table column names
["id", "visit_id", "user_id", "name", "properties", "time"]
can anyone help me out in this
Expected output something like this
{ 21 => "2018-12-18 09:44:59", 42 => "2018-12-19 12:08:59"}
21 is user_id and value is last visit time
Using mysql as database
So you want all user visits with last visited time.
Instead of use DISTINCT function, you can use GROUP with MAX function.
Query looks like
Events.group(:user_id).maximum(:time)
This Outputs your desired results
{21=>Tue, 18 Dec 2018 11:15:24 UTC +00:00, 23=>Thu, 20 Dec 2018 06:42:10 UTC +00:00}
Hope this works for you.
FYI
DISTINCT ON(columns). is PostgreSQL Syntax.
Like i said in the comments DISTINCT ON(column), * is PostgreSQL SQL syntax.
The query below you need to have to rewrite in MySQL
SELECT
DISTINCT ON(user_id) AS user_id, time
FROM
<table>
ORDER BY
time DESC
LIMIT 11
The most easy to do that is using SUBSTRING_INDEX(GROUP_CONCAT(..)).
The queries below should give you the correct results.
SET SESSION group_concat_max_len = ##max_allowed_packet;
SELECT
user_id
, SUBSTRING_INDEX(
GROUP_CONCAT(time
ORDER BY
time DESC
)
, ','
, 1
) AS time
FROM
<table>
GROUP BY
user_id
ORDER BY
time DESC
LIMIT 11
Related
SELECT TOP (2)
DATEPART(HOUR,t.callerDateTime) as Hour
,count(cli) as Count
FROM ivrtimeout t
where convert(date,t.callerDateTime) = convert(date,getdate(),103)
group by DATEPART(HOUR,t.callerDateTime)
order by DATEPART(HOUR,t.callerDateTime) desc
Above Query is working fine in case of Microsoft SQL Server and giving error using in xamp server maria-db.
Can anyone please make correction?
Try this:
select
extract(HOUR from callerDateTime) as Hour,
count(cli) as Count
from ivrtimeout
where callerDateTime >= timestamp(current_date)
group by 1
order by 1 desc
limit 2
I have this query (take a look on between dates):
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between (STR_TO_DATE('11/24/2020','%m/%d/%y'))
and (STR_TO_DATE('12/26/2021','%m/%d/%y'))
GROUP BY user_name ;
The select is between dates:
startDate: (STR_TO_DATE('11/24/2020','%m/%d/%y'))
finishDate: (STR_TO_DATE('12/26/2021','%m/%d/%y'))
This query will return something because there are records on year 2020
the problem is when i change the month of the finishDate, i tried with:
finishDate: (STR_TO_DATE('1/26/2021','%m/%d/%y')) = null
finishDate: (STR_TO_DATE('01/26/2021','%m/%d/%y')) = null
finishDate: (STR_TO_DATE('10/26/2021','%m/%d/%y')) = null
It just makes no sense... im using mysql community 8.0.20
Since the problem only occurs in the finsihDate perhaps this could be helpful.
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between (STR_TO_DATE('11/24/2020','%m/%d/%y'))
and (DATE_ADD(STR_TO_DATE('11/24/2020','%m/%d/%y'), INTERVAL 367 DAY))
GROUP BY user_name ;
Of course you should check for relevant errors or warnings in MySQL server logs, that could explain the problem for finsihDate.
********UPDATE SOLUTION:
for some unknown reason my db IDE shows the date with this format "$DAY/$MONTH/$YEAR" even if insert the right DATE MYSQL FORMAT ("$YEAR-$MONTH-$DAY)
i got the following warnings:
And this is the final query that worked but your solution did worked as well:
SELECT user_name, COUNT(*) AS 'COUNT'
FROM user_records
WHERE date_created between '2020-11-24' AND '2021-01-24'
GROUP BY user_name ;
The problem with your query is the date format. Lowercase '%y' matches a two digit year. So, only the first two characters from 2021 are used for the year -- and you have the wrong year.
But, that is not the real problem. You don't need str_to_date(). Just use properly formatted date literals.
Assuming that the dates are stored correctly as date data types, then you can simply use:
SELECT user_name, COUNT(*) AS COUNT
FROM user_records
WHERE date_created between '2020-11-24' and '2021-12-26'
GROUP BY user_name ;
If date_created is stored as a string, then fix your data model so it is either a date or datetime. Dates should not be stored as strings.
I have the following columns in my database:
- day
- browser
- platforms
- visitors_number
I have to choose the day of the week for which the average number of visitors was maximum and display this maximum average. I searched the forum, found a similar thread, but the solution does not work, I get an error. I would add that I am sitting on it for the second day and I lack ideas. I will add that it works on phpMyAdmin.
This is my code:
select DAYNAME(DAY), avgVIS
from
(
select DAYNAME(DAY), avg(VISITORS_NUMBER) as avgVIS
from dane_2
group by DAYNAME(DAY)
)
where avgVIS = (select max(avgVIS)
from ( select DAYNAME(DAY), avg(VISITORS_NUMBER) as avgVIS
from dane_2
group by DAYNAME(DAY)))
this is output's error
#1064 - Something is wrong in your syntax obok 'where avgVIS = (select max(avgVIS)
from ( select DAYNAME(DAY), a'
Can someone helps me ?
Thank you in advance
You already have the aggregation query that computes the daily average. All that is let to do is sort and limit:
select dayname(d.DAY) day_name, avg(d.VISITORS_NUMBER) avg_vis
from dane_2 d
group by dayname(d.DAY)
order by avg_vis desc
limit 1
Note: DAY is a reserved word in MySQL, so not a good choice for a column name (I qualified it with the table alias to avoid errors).
i have an question how to use an "alias" column at the where/having clause. I know there are some question with an related topic. But I search trough the web and on stackoverfolw and doesn't find an solution.
So i hope for help at this way..
The following statement works well:
SELECT PHRASE,COUNT(*) AS A
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
GROUP BY PHRASE ORDER BY A DESC
LIMIT 16;
PHRASE and TIMESTAMPare columns at the table.
The code selects the top 16 PHRASES, which are inserts by users on the last 7 days.
There are also exist an column USER and so i like now to select the top 16 phrases which are inserted by more than one user.
So i tried this:
SELECT PHRASE,COUNT(*) AS A, COUNT(DISTINCT(USER)) AS B
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
AND B>1
GROUP BY PHRASE ORDER BY A DESC
LIMIT 16;
On other questions on stackoverflow i fond the info, that i have to use HAVING
SELECT PHRASE,COUNT(*) AS A, COUNT(DISTINCT(USER)) AS B
FROM my_statistics
WHERE TIMESTAMP>NOW()-INTERVAL 7 DAY
GROUP BY PHRASE ORDER BY A DESC
HAVING B>1
LIMIT 16;
But this returns an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'HAVING B>1
LIMIT 16' at line 5
I have no idea, how the right syntax could be.
Hope for any kind of help here.
Thank you!
Place the ORDER BY A DESC after Having clause.
SELECT phrase,
Count(*) AS A,
Count(DISTINCT( user )) AS B
FROM my_statistics
WHERE timestamp > Now() - INTERVAL 7 day
GROUP BY phrase
HAVING b > 1
ORDER BY a DESC
LIMIT 16;
I have an unavoidable situation where the dates are stored in UK date format, e.g.:
31/12/2001 00:00:00
I need it in descending order, I've tried this but it errors
select *, DATE_FORMAT(completiondate,'\%e/%c/%Y\') as cdate
from projects
where countries = 1
order by cdate desc
Error:
check the manual that corresponds to your MySQL server version for the
the right syntax to use near '' order by cdate desc'
I'm using MySQL 4.1.9
This was the end solution
select *,completiondate from projects order by str_to_date(completiondate,'%d/%m/%Y %H:%i') desc
You are escaping the % character unnecessarily. But the actual problem is that that you have an un-terminated string literal in your query:
-- this does not terminate the string ----------v
select *, DATE_FORMAT(completiondate,'\%e/%c/%Y\') as cdate
from projects
where countries = 1
order by cdate desc
Change to:
SELECT *, DATE_FORMAT(completiondate,'%e/%c/%Y') AS cdate
FROM projects
WHERE countries = 1
ORDER BY cdate DESC
Jim, your end solution was a huge help for me. My dates are in the 02/28/2013 format. I used the code:
SELECT *,str_to_date(SaleDate,'%m/%d/%Y') AS cdate FROM mytable ORDER BY cdate DESC
Thanks!
SELECT * FROM projects WHERE countries = 1 order by cdate desc
I'm guessing you have cdate already in your database? If so, you don't need to set "date_format" since it's already there.
But I may be wrong since I've never used 4.1.9