Selecting a Subquery - mysql

I've been bugging this for the past hour..
I want to get the TOP 5 from latest data from my table clickednumbers
clickednumbers has only to columns numbers as INT & numberTime as timestamp
My query
SELECT AVG( SELECT *
FROM clickednumbers
ORDER BY numberTime DESC
LIMIT 5)
FROM clickednumbers
and im always getting the error
#1064 - You have an error in your SQL syntax;check the manual that corresponds to your MariaDB server version for the right syntanx to use near
'SELECT *
FROM clicked numbers
ORDER BY numberTime DESC '
at line 1
MariaDB Version:Server type: MariaDB
Server version: 10.1.9-MariaDB - mariadb.org binary distribution
Protocol version: 10
Sorry for bothering :(
Goal : To get the average of top 5 from latest numbers based on the numbersTime

To get the average of the top 5, use a subquery in the FROM clause:
SELECT AVG(numbers)
FROM (SELECT *
FROM clickednumbers
ORDER BY numberTime DESC
LIMIT 5
) cn;

Check this out for more of an idea what's going on. I think your query needs to look more like this:
SELECT AVG(x.numbers)
FROM (SELECT numbers FROM clickednumbers ORDER BY numberTime DESC
LIMIT 5) as x

Related

SQL Query correction required

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

How to use variable in LIMIT statement in MYSQL?

I am trying to return the median by using order by and returning the mid element. I am using limit to offest the first half and then return 1 row which will give median.
SELECT
COUNT(*) into #cnt FROM STATION;
SELECT ROUND(LAT_N,4)
FROM STATION
ORDER BY LAT_N
LIMIT 1 OFFSET ((#cnt-1)/2)
I am getting error:-
ERROR 1064 (42000) at line 6: 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 '((#cnt-1)/2)' at line 4
Total no of rows = 499
so if I use
SELECT
COUNT(*) into #cnt FROM STATION;
SELECT ROUND(LAT_N,4)
FROM STATION
ORDER BY LAT_N
LIMIT 1 OFFSET 250
I don't get any error. SO why is error on first one?
SO why is error on first one?
Well, you will get an error if you make it a fair comparison by writing..
... OFFSET ((501-1)/2)
MySQL after 5.5 can parameterize LIMIT and OFFSET if you pass integer variables for them
Make it OFFSET #cnt and get your front end to do the calc for #cnt
I suggest to modify your query like this:
SELECT
COUNT(*) into #cnt FROM STATION;
SELECT ROUND(LAT_N,4)
FROM STATION
ORDER BY LAT_N
LIMIT 1 OFFSET (#cnt - 1) / 2 ROWS FETCH NEXT 2 - #cnt % 2 ROWS ONLY )

how to use DISTINCT ON with mysql using ActiveRecord

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

mysql using calculated column at where/having

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;

Mysql sort date format

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