I need to order my query by date first...
So I used this:
SELECT * FROM `mfw_navnode` order by `id` DESC
I wanted to order my results from last to first.
Then what I am trying to do
is to add a query over it, which would group my results by node_name..
The result should be..all the top nodes grouped by "category/node name type", while the first node that I see is was ordered the highest for its category in the first query..
I thought to do something like this:
SELECT * FROM(
SELECT * FROM `mfw_navnode` order by `id` DESC) AS DD
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
I get no result..or any response from phpmyadmin when I input that result..
Where do I get wrong?
Note , I dont want to group my results and then order them..
I want them to be ordered, and then grouped. After being grouped..I want the result of each group to have the highest value ..from the other rows in the group
It is not sufficient to perform the ordering first, as even then MySQL makes no guarantee over which record it will select for each group. From the manual:
The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate.
You must instead identify the records of interest with a subquery, then join the result with your table again in order to obtain the related values:
SELECT *
FROM mfw_navnode NATURAL JOIN (
SELECT node_name, MAX(id) AS id FROM mfw_navnode GROUP BY node_name
) AS DD
WHERE node_name IN ('Eby', 'Laa', 'MIF', 'Amaur', 'Asn')
Ordered by ID and group by node_name
SELECT * FROM `mfw_navnode`
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
ORDER BY `id` DESC
Grouping is used commonly when You are using some aggregate function (sum, max, min, count, etc). If You don't use such function in Your query then why do You want to group the results?
Anyway, this should do the trick:
SELECT *
FROM mfw_navnode
WHERE id IN (SELECT id
FROM mfw_navnode
WHERE node_name IN ('Eby', 'Laa', 'MIF', 'Amaur', 'Asn')
GROUP BY node_name)
ORDER BY id
The following SQL may yield you the required output:
SELECT node_name, MAX(id)
FROM mfw_navnode
GROUP BY node_name
ORDER BY node_name
I see two problems with your SQL.
1) placing the order by in the inline select does nothing (and is probably causing an error)
2) you are grouping on node_name but you are not aggregating anything
SELECT COUNT(id) as row_count, node_name FROM( SELECT * FROM mfw_navnode ) AS DD
WHERE (node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn' )
GROUP BY DD.node_name
order by node_name desc
further I am not sure why you need the inline select as the where could simply be on the original select ( perhaps you have something more complex going on that you didn't show )
SELECT COUNT(id) as row_count, node_name
from mfw_navnode
WHERE node_name='Eby' OR node_name='Laa' OR node_name='MIF' OR node_name='Amaur' OR node_name='Asn'
GROUP BY node_name
order by node_name desc
Related
I have been struggling to set this up for months and months!
I need help with setting rank to my database.
This is how my current code looks like:
$db->queryNoReturn("SET #a:=0");
return $db->query("
SELECT * FROM
(SELECT
`FFA_Stats`.`id`,
`FFA_Stats`.`player_uuid`,
`FFA_Stats`.`points`,
`FFA_Stats`.`hits`,
`FFA_Stats`.`shots`,
`FFA_Stats`.`wins`,
`FFA_Stats`.`tkills`,
`FFA_Stats`.`tdeaths`,
(`FFA_Stats`.`tkills`/`FFA_Stats`.`tdeaths`) as `KDR`,
`player`.`name`,
`player`.`uuid`,
`player`.`online`,
(#a:=#a+1) AS rank
FROM `FFA_Stats`
INNER JOIN `player` ON `FFA_Stats`.`player_uuid`=`player`.`uuid`
ORDER BY `points` DESC
) AS `sub`
");
Basically its sorting it by points and you can check how it looks like here: http://filipvlaisavljevic.com/clash/ffa.php
All I want to do is add rank to the sorted table so the player with the most points would be #1 etc.
Does anyone know what to do?
Usually a rank number would be an integer that you could generate from iterating through the rows of the query result. eg. echo $count++;
If you have calculated or attributed a rank in your database then you can add 'order by' statements separated by commas. eg.
FROM `FFA_Stats`
INNER JOIN `player`
ON `FFA_Stats`.`player_uuid`=`player`.`uuid`
ORDER BY `rank` DESC, `points` DESC) AS `sub`
");
How can I find the most frequent value in a given column in an SQL table?
For example, for this table it should return two since it is the most frequent value:
one
two
two
three
SELECT
<column_name>,
COUNT(<column_name>) AS `value_occurrence`
FROM
<my_table>
GROUP BY
<column_name>
ORDER BY
`value_occurrence` DESC
LIMIT 1;
Replace <column_name> and <my_table>. Increase 1 if you want to see the N most common values of the column.
Try something like:
SELECT `column`
FROM `your_table`
GROUP BY `column`
ORDER BY COUNT(*) DESC
LIMIT 1;
Let us consider table name as tblperson and column name as city. I want to retrieve the most repeated city from the city column:
select city,count(*) as nor from tblperson
group by city
having count(*) =(select max(nor) from
(select city,count(*) as nor from tblperson group by city) tblperson)
Here nor is an alias name.
Below query seems to work good for me in SQL Server database:
select column, COUNT(column) AS MOST_FREQUENT
from TABLE_NAME
GROUP BY column
ORDER BY COUNT(column) DESC
Result:
column MOST_FREQUENT
item1 highest count
item2 second highest
item3 third higest
..
..
For use with SQL Server.
As there is no limit command support in that.
Yo can use the top 1 command to find the maximum occurring value in the particular column in this case (value)
SELECT top1
`value`,
COUNT(`value`) AS `value_occurrence`
FROM
`my_table`
GROUP BY
`value`
ORDER BY
`value_occurrence` DESC;
Assuming Table is 'SalesLT.Customer' and the Column you are trying to figure out is 'CompanyName' and AggCompanyName is an Alias.
Select CompanyName, Count(CompanyName) as AggCompanyName from SalesLT.Customer
group by CompanyName
Order By Count(CompanyName) Desc;
If you can't use LIMIT or LIMIT is not an option for your query tool. You can use "ROWNUM" instead, but you will need a sub query:
SELECT FIELD_1, ALIAS1
FROM(SELECT FIELD_1, COUNT(FIELD_1) ALIAS1
FROM TABLENAME
GROUP BY FIELD_1
ORDER BY COUNT(FIELD_1) DESC)
WHERE ROWNUM = 1
If you have an ID column and you want to find most repetitive category from another column for each ID then you can use below query,
Table:
Query:
SELECT ID, CATEGORY, COUNT(*) AS FREQ
FROM TABLE
GROUP BY 1,2
QUALIFY ROW_NUMBER() OVER(PARTITION BY ID ORDER BY FREQ DESC) = 1;
Result:
Return all most frequent rows in case of tie
Find the most frequent value in mysql,display all in case of a tie gives two possible approaches:
Scalar subquery:
SELECT
"country",
COUNT(country) AS "cnt"
FROM "Sales"
GROUP BY "country"
HAVING
COUNT("country") = (
SELECT COUNT("country") AS "cnt"
FROM "Sales"
GROUP BY "country"
ORDER BY "cnt" DESC,
LIMIT 1
)
ORDER BY "country" ASC
With the RANK window function, available since MySQL 8+:
SELECT "country", "cnt"
FROM (
SELECT
"country",
COUNT("country") AS "cnt",
RANK() OVER (ORDER BY COUNT(*) DESC) "rnk"
FROM "Sales"
GROUP BY "country"
) AS "sub"
WHERE "rnk" = 1
ORDER BY "country" ASC
This method might save a second recount compared to the first one.
RANK works by ranking all rows, such that if two rows are at the top, both get rank 1. So it basically directly solves this type of use case.
RANK is also available on SQLite and PostgreSQL, I think it might be SQL standard, not sure.
In the above queries I also sorted by country to have more deterministic results.
Tested on SQLite 3.34.0, PostgreSQL 14.3, GitHub upstream.
Most frequent for each GROUP BY group
MySQL: MySQL SELECT most frequent by group
PostgreSQL:
Get most common value for each value of another column in SQL
https://dba.stackexchange.com/questions/193307/find-most-frequent-values-for-a-given-column
SQLite: SQL query for finding the most frequent value of a grouped by value
SELECT TOP 20 WITH TIES COUNT(Counted_Column) AS Count, OtherColumn1,
OtherColumn2, OtherColumn3, OtherColumn4
FROM Table_or_View_Name
WHERE
(Date_Column >= '01/01/2023') AND
(Date_Column <= '03/01/2023') AND
(Counted_Column = 'Desired_Text')
GROUP BY OtherColumn1, OtherColumn2, OtherColumn3, OtherColumn4
ORDER BY COUNT(Counted_Column) DESC
20 can be changed to any desired number
WITH TIES allows all ties in the count to be displayed
Date range used if date/time column exists and can be modified to search a date range as desired
Counted_Column 'Desired_Text' can be modified to only count certain entries in that column
Works in INSQL for my instance
One way I like to use is:
select *<given_column>*,COUNT(*<given_column>*)as VAR1 from Table_Name
group by *<given_column>*
order by VAR1 desc
limit 1
i have a problem my database looks like this DATABASE STRUCTURE
i want to sort the lboard and ignore the repeated values
like this REQUIRED OUTPUT
can anyone help me?
You could use GROUP BY to get single result for one user and MAX function to get its maximum score
the query will be like this
SELECT id, exam_id, user_id, MAX(lboard) FROM `leaderb` GROUP BY user_id ORDER BY lboard DESC
SELECT id, exam_id, user_id, MAX( lboard )
FROM wp_watu_takings WHERE exam_id = 3
GROUP BY user_id
ORDER BY MAX( lboard ) DESC
I am trying to get data from my table using group by . using group by works correctly but i need to take only last inserted item of every group but its not work. my query always return first item of each group.
my query
SELECT id,type,userId,performDate,eventId FROM
`user_marker` where `eventId`='842' and DATE_FORMAT(from_unixtime(performDate),'%Y%c%d')
=DATE_FORMAT(now(),'%Y%c%d')
and `visibility`='1'GROUP BY type ORDER BY id DESC
Please try
SELECT a.* FROM ( SELECT id,type,userId,performDate,eventId FROM
`user_marker` where `eventId`='842' and DATE_FORMAT(from_unixtime(performDate),'%Y%c%d')
=DATE_FORMAT(now(),'%Y%c%d') and `visibility`='1' ORDER BY id DESC ) as a GROUP BY a.type
You can try as per below-
SELECT b.id,b.type,b.userId,b.performDate,b.eventId
FROM user_marker b
JOIN (SELECT `type`,MAX(performDate)
FROM user_marker
WHERE `eventId`='842' AND DATE(FROM_UNIXTIME(performDate))=CURDATE() AND `visibility`='1'
GROUP BY `type`) a ON a.type=b.type AND a.performDate=b.performDate
ORDER BY b.`type`;
I have an table like this
I have been try this sql code
SELECT id,lat,lng,name,MIN(hitung) AS Smallest FROM open_list;
but the result give me wrong query
what i wanna do is being like this :
You could do this:
SELECT id,lat,lng,name,hitung
FROM open_list
ORDER BY hitung ASC
LIMIT 1
Or, if you want to do more complex stuff, start with this:
SELECT id,lat,lng,name,hitung
FROM open_list
JOIN (
SELECT MIN(hitung) as hitung
FROM open_list
) tmp USING (hitung)
When you do not GROUP BY non-aggregate values from your SELECT list, the returned values are arbitrary. You can add a GROUP BY but that will return multiple records, you can use ORDER BY and LIMIT to get what you're after:
SELECT id,lat,lng,name,hitung
FROM open_list
GROUP BY id,lat,lng,name
ORDER BY hitung ASC
LIMIT 1;