SQL data sorting _ MySQL

Source: Internet
Author: User
SQL data sorting-Test table
Create table Test (F1 char (10), F2 char (10 ))

-- Insert data
Insert into Test
SELECT 'A' F1, '1' F2
UNION
SELECT 'B' F1, '2' F2
UNION
SELECT 'C' F1, '4' F2
UNION
SELECT 'D' F1, '3' F2
UNION
SELECT 'E' F1, '4' F2
UNION
SELECT 'F' F1, '5' F2
UNION
SELECT 'G' F1, '4' F2
UNION
SELECT 'h'f1, '7' F2
UNION
SELECT 'I 'F1, '9' F2

--- Ranking
-- Method 1
SELECT a. *, (select count (*) FROM test B WHERE B. F2> a. F2) + 1 AS minci FROM test a ORDER BY minci
-- Method 2
SELECT id = IDENTITY (int, 0, 1), f1, f2 INTO # t FROM test order by F2 DESC
SELECT a. f1, a. f2, a. id + 1-cast (id-cc-minn AS Char (10) AS [ranking]
FROM # t a, (SELECT f2, cc, minn FROM (SELECT f2, COUNT (*) AS cc, MIN (id)-COUNT (*) AS minn FROM # t group by f2) t) B
WHERE a. f2 = B. f2
Order by a. f2 DESC

-- Delete a table
Drop table # t
Drop table test

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.