phymyadmin add row number in query result - php

Hi i have this sql code i want to query in phpmyadmin
SELECT DISTINCT `unit`,`location` FROM `myasset` ORDER BY `unit` asc
It is possible to add custom number in my sql result
I tried something like below..its not working ..i received message row_number function does not exist
SELECT DISTINCT Row_Number(),`unit`,`location` FROM `myasset` ORDER BY `unit`
SELECT Row_Number() DISTINCT`unit`,`location` FROM `myasset` ORDER BY `unit`

First you have to set a value like
SET #rnum = 0;
then
SELECT #rnum:=#rnum+1 AS row_num, DISTINCT unit,location FROM myasset ORDER BY unit asc
Hope it will solve your issue.
Thanks

You could do
select #rownum:=#rownum+1 No,DISTINCT unit,location FROM myasset ORDER BY unit, (SELECT #rownum:=0);

Related

Need to perform ORDER BY twice, problems with ranking

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`
");

Select most common value? [duplicate]

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

Get Wrong Query when usin MIN in sql

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;

Mysql ordering and then grouping a query in mysql

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

SQL position of row(ranking system) WITHOUT same rank for two records

so I'm trying to create a ranking system for my website, however as a lot of the records have same number of points, they all have same rank, is there a way to avoid this?
currently have
$conn = $db->query("SELECT COUNT( * ) +1 AS 'position' FROM tv WHERE points > ( SELECT points FROM tv WHERE id ={$data['id']} )");
$d = $db->fetch_array($conn);
echo $d['position'];
And DB structure
`id` int(11) NOT NULL,
`name` varchar(150) NOT NULL,
`points` int(11) NOT NULL,
Edited below,
What I'm doing right now is getting records by lets say
SELECT * FROM tv WHERE type = 1
Now I run a while loop, and I need to make myself a function that will get the rank, but it would make sure that the ranks aren't duplicate
How would I go about making a ranking system that doesn't have same ranking for two records? lets say if the points count is the same, it would order them by ID and get their position? or something like that? Thank you!
If you are using MS SQL Server 2008R2, you can use the RANK function.
http://msdn.microsoft.com/en-us/library/ms176102.aspx
If you are using MySQL, you can look at one of the below options:
http://thinkdiff.net/mysql/how-to-get-rank-using-mysql-query/
http://www.fromdual.ch/ranking-mysql-results
select #rnk:=#rnk+1 as rnk,id,name,points
from table,(select #rnk:=0) as r order by points desc,id
You want to use ORDER BY. Applying on multiple columns is as simple as comma delimiting them: ORDER BY points, id DESC will sort by points and if the points are the same, it will sort by id.
Here's your SELECT query:
SELECT * FROM tv WHERE points > ( SELECT points FROM tv WHERE id ={$data['id']} ) ORDER BY points, id DESC
Documentation to support this: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html
Many Database vendors have added special functions to their products to do this, but you can also do it with straight SQL:
Select *, 1 +
(Select Count(*) From myTable
Where ColName < t.ColName) Rank
From MyTable t
or to avoid giving records with the same value of colName the same rank, (This requires a key)
Select *, 1 +
(Select Count(Distinct KeyCol)
From myTable
Where ColName < t.ColName or
(ColName = t.ColName And KeyCol < t.KeyCol)) Rank
From MyTable t

Categories