简体   繁体   中英

How do I sort by a new generated column in mySQL?

I have to sort some information that is encoded in the following form: GTEX-VJYA-2126-SM-4KL1O I have a list of this IDs and I have to take the first two strings separated by '-' (so,GTEX-VUSG) and count how many of each distinct ID I end up with.

I'm using the following MySQL code:

mysql> SELECT SUBSTRING_INDEX(SAMPID,'-',2), COUNT(*) FROM GTEX_Sample GROUP BYSUBSTRING_INDEX(SAMPID, '-',2);

And I'm getting the following result:

| GTEX-ZXG5                     |       21 |
| GTEX-ZY6K                     |       19 |
| GTEX-ZYFC                     |       20 |
| GTEX-ZYFD                     |       19 |
| GTEX-ZYFG                     |       25 |
| GTEX-ZYT6                     |       26 |
| GTEX-ZYVF                     |       20 |
| GTEX-ZYW4                     |       20 |
| GTEX-ZYWO                     |       25 |
| GTEX-ZYY3                     |       21 |
| GTEX-ZZ64                     |       20 |
| GTEX-ZZPT                     |       12 |
| GTEX-ZZPU                     |       23 |
| K-562                         |      217

Now I need to sort this result by the new generated column (the second one), but since is new I don't know how to use the 'order by' command. Is there any way to do it?

Just repeat the expression in the ORDER BY clause:

SELECT SUBSTRING_INDEX(SAMPID,'-',2), COUNT(*) 
FROM GTEX_Sample 
GROUP BY SUBSTRING_INDEX(SAMPID, '-',2) 
ORDER BY COUNT(*) DESC

You could also alias the column in the SELECT clause, and use that to sort:

SELECT SUBSTRING_INDEX(SAMPID,'-',2), COUNT(*) AS CNT
FROM GTEX_Sample 
GROUP BY SUBSTRING_INDEX(SAMPID, '-',2) 
ORDER BY CNT DESC

Note that MySQL extends the SQL standard by allowing column aliases in the GROUP BY clause. This lets you do something like:

SELECT SUBSTRING_INDEX(SAMPID,'-',2) AS SUBSAMPID, COUNT(*) AS CNT
FROM GTEX_Sample 
GROUP BY SUBSAMPID 
ORDER BY CNT DESC

GMB has the right answer.

Order by also takes positional parameters like

SELECT SUBSTRING_INDEX(SAMPID,'-',2), COUNT(*) FROM GTEX_Sample GROUP BYSUBSTRING_INDEX(SAMPID, '-',2) ORDER BY 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM