Select a table values ordered by two field [duplicate] - php

How can I sort by multiple columns in SQL and in different directions. column1 would be sorted descending, and column2 ascending.

ORDER BY column1 DESC, column2
This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.

The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706

SELECT *
FROM mytable
ORDER BY
column1 DESC, column2 ASC

Multiple column ordering depends on both column's corresponding values:
Here is my table example where are two columns named with Alphabets and Numbers and the values in these two columns are asc and desc orders.
Now I perform Order By in these two columns by executing below command:
Now again I insert new values in these two columns, where Alphabet value in ASC order:
and the columns in Example table look like this.
Now again perform the same operation:
You can see the values in the first column are in desc order but second column is not in ASC order.

You can use multiple ordering on multiple condition,
ORDER BY
(CASE
WHEN #AlphabetBy = 2 THEN [Drug Name]
END) ASC,
CASE
WHEN #TopBy = 1 THEN [Rx Count]
WHEN #TopBy = 2 THEN [Cost]
WHEN #TopBy = 3 THEN [Revenue]
END DESC

SELECT id,
first_name,
last_name,
salary
FROM employee
ORDER BY salary DESC, last_name;
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY. This clause comes at the end of your SQL query.
After the ORDER BY keyword, add the name of the column by which you’d like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name). You can modify the sorting order (ascending or descending) separately for each column. If you want to use ascending (low to high) order, you can use the ASC keyword; this keyword is optional, though, as that is the default order when none is specified. If you want to use descending order, put the DESC keyword after the appropriate column (in the example, we used descending order for the salary column).

SELECT * FROM EMP ORDER BY DEPTNO ASC, JOB DESC;

TRY
'select * FROM users ORDER BY id DESC, name ASC, age DESC

You can also sort or order by the Number of Characters in each Column you wish to sort by. Shown below is a sample which sorts by the first three characters of the First Name and by the last two characters in the name of the town.
SELECT *
FROM table_name
ORDER BY LEFT(FirstName, 3) ASC, LEFT(Town, 2);

Related

MySQL - I need to SELECT the highest umber in a column when there are multiple ID's

Take the following dataset:
id | Number
1 | 6534
1 | 765
1 | 1234
2 | 744
2 | 6109
3 | 333
3 | 9888
3 | 3112
3 | 98432
I want to show the highest Number for each id.
So Like this:
id | Number
1 | 6534
2 | 6109
3 | 98432
How can I do this with a SELECT statement?
I've already tried the following:
SELECT * FROM mytable ORDER BY id, Number Desc
But this shows the entire dataset.
I'm not trying to get the number of occurences. I am trying to get the highest Number grouped by id but can't get it to work.
SELECT id, MAX(Number) as Number FROM mytable GROUP BY id
You can try :
Select id,max(Number) from Your_Table group by id
Your Query that you have tried, it will only order your Data table by the given parameters.
In the meantime, What i have proposed to you, will select the two columns you want to diplay (the id, and the maximum of the column "Number").
And the group by will help to the maximum of each group. That's why a group by id is the right clause to have the maximum of each group of Ids.
Most of time the id field is incremental but for your case you can use.
SELECT MAX(number) FROM `user` GROUP BY id
Where number is the column name from which you want to find MAX, and user is your table name.

Select distinct by highest or lowest value

I'm working on a track and field ranking database in MySQL/PHP5 whereby I'm struggling to find the best way to query results per unique athlete by highest value.
just
SELECT distinct name, event
FROM results
sample database
name | event | result
--------------------------
athlete 1 | 40 | 7.43
athlete 2 | 40 | 7.66
athlete 1 | 40 | 7.33
athlete 1 | 60 | 9.99
athlete 2 | 60 | 10.55
so let's say that in this case I'd like to rank the athletes on the 40m dash event by best performance I tried
SELECT distinct name, event
FROM results
WHERE event = 40
ORDER by result DESC
but the distinct only leaves the first performance (7.43) of the athlete which isn't the best (7.33). Is there an easy way other than creating a temp table first whereby the results are ordered first and performing a select on the temp table afterwards?
You might be interested in group by:
SELECT name, min(result) as result
FROM results
WHERE event = 40
GROUP BY name
This gives you the best result per athlete.
As suggested by spencer, you can also order the list by appending this:
ORDER BY min(result) ASC
The problem is that the columns used in the ORDER BY aren't specified in the DISTINCT. To do this, you need to use an aggregate function to sort on, and use a GROUP BY to make the DISTINCT work.
SELECT distinct name, event
FROM results
WHERE event = 40
GROUP BY name
ORDER by result DESC

How to Group by user_id and order by desc

Hello i am aware this is very basic but right now i am so confused i want to GROUP BY user_id ORDER BY id DESC LIMIT 4 (i have posted short example of table and my query)
My table looks like where id is auto increment i only save user_id i only want to take one user_id only once which is lastest entry in database ignore other.
Table
---------------------
id | user_id |
---------------------
13 | 25 |
12 | 36 |
11 | 25 |
10 | 42 |
9 | 95 |
8 | 25 |
7 | 95 |
---------------------
so on
I have tried this
SELECT * FROM `table` GROUP BY user_id ORDER BY `id` DESC LIMIT 4
I want it to output 25,36,42,95 i have also tried many experiments but nothing seems to be working.
Do i need timestamp or something to make it in group? or what query will work?
You are doing a partial GROUP BY which does not work the way you expect. Here is a query which produces the desired results:
SELECT MAX(id) AS MAXID, user_id
FROM `table`
GROUP BY user_id
ORDER BY MAXID DESC
LIMIT 4
The behavior is explained here:
MySQL extends the use of GROUP BY so that the select list can refer to
nonaggregated columns not named in the GROUP BY clause. [...] You can
use this feature to get better performance by avoiding unnecessary
column sorting and grouping. However, this is useful primarily when
all values in each nonaggregated column not named in the GROUP BY are
the same for each group. The server is free to choose any value from
each group, so unless they are the same, the values chosen are
indeterminate. Furthermore, the selection of values from each group
cannot be influenced by adding an ORDER BY clause. Sorting of the
result set occurs after values have been chosen, and ORDER BY does not
affect which values within each group the server chooses.
In your example you need to get result like 25,36,42,95, but sort by ID field.
If you will sort by it you will get different result.
You get a grouping in your query so you cannot use columns that not chosen in query (id is ommited there)
If you still need to order by id, i think that you need to add order by MAX('id') or MIN('id')
In your case i`ll make next query:
SELECT user_id FROM `table` GROUP BY user_id ORDER BY MAX(`id`) DESC LIMIT 4
Try this
SELECT MAX(id) as countid , `user_id` from `table`
GROUP BY `user_id`
ORDER BY countid DESC
LIMIT 20
In stead of grouping, you can use distinct, like below sql query.
SELECT distinct(user_id) FROM `table` ORDER BY `id` DESC LIMIT 4
SELECT * FROM (
SELECT 13 id, 25 UserID
UNION ALL
SELECT 12 id, 36 UserID
UNION ALL
SELECT 11 id, 25 UserID
UNION ALL
SELECT 10 id, 42 UserID
UNION ALL
SELECT 09 id, 95 UserID
UNION ALL
SELECT 08 id, 25 UserID
UNION ALL
SELECT 07 id, 95 UserID
) a
GROUP BY userid ORDER BY id DESC LIMIT 4

Count/Group By/Order By is only showing the count of the most common value and not the string itself

I'm querying a table to find the most common string in a column. However, it doens't seem to be working correctly. It should be returning the value of the most common string, but is instead returning the number of times the most common string exists. The query is:
SELECT COUNT(field_review_bar_tab_2_value) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1
Table structure, simplified, would be something to the effect of:
-----------------------------------
| ID | field_review_bar_tab_2_value |
|----+----------------------------- |
| 1 | Food Drinks |
| 2 | Drinks |
| 3 | Food Drinks |
| 4 | Food |
-----------------------------------
The query is recognizing that, in the example above, "Food Drinks" is the most common string in the column. But, the query is returning "2" instead of "Food Drinks". Any ideas as to why it would be making the correct query but returning the count of the result instead of the value of the string?
You need to include field_review_bar_tab_2_value in the SELECT list as well. I've switched the aggregate to COUNT(*) here, and included the grouped column in the SELECT.
SELECT
field_review_bar_tab_2_value AS the_most_common_string,
COUNT(*) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1
You're selecting the count, not the value. I think you mean:
SELECT field_review_bar_tab_2_value
FROM field_data_field_review_bar_tab_2
GROUP BY field_review_bar_tab_2_value
ORDER BY COUNT(*) DESC
LIMIT 1
Since you're already grouping by the value in question, you can just do COUNT(*)...
You will need to modify your query to return the field itself. Currently the query is only returning the COUNT because that's what is indicated in your select statement. Modify it as follows:
SELECT field_review_bar_tab_2_value AS `MostCommonString`, COUNT(field_review_bar_tab_2_value) AS `Rows`
FROM (field_data_field_review_bar_tab_2)
GROUP BY (field_review_bar_tab_2_value)
ORDER BY `Rows` DESC
LIMIT 1

Mysql select order by acts like a string, not a number

How do you order by number if your number can fall below and be bigger than 0?
Example Mysql table:
|Name|Karma|
__________
|Me | -8 |
|Bill| 5 |
|Tom | 2 |
|Saly| 0 |
|San.| -3 |
Example select query
$sql="SELECT karma FROM table ORDER BY karma DESC";
The result I get is this (separated by comma): 5,2,0,-8,-3.
Shouldn't it be 5,2,0,-3,-8?
I discovered somewhere in the internet that mysql orders by string. How to make it order by number?
Karma will be ordered as a string if you have made it a string, i.e. a varchar column.
Convert the column to a INT, and it will order numerically.
You also have the option of not changing the table, but casting the column into the right type while sorting:
SELECT karma FROM table ORDER BY CAST(karma AS int) DESC
but that is bad for performance.
There's another weirdest option:
SELECT karma FROM table ORDER BY karma+0 DESC

Categories