SQL项目排序需求咨询:按借款人姓名及贷款日期排序
No problem at all! To get the output you want—first sorted alphabetically by borrower name, then with the newest loan dates at the top for each borrower—you'll use SQL's ORDER BY clause with two layered sorting criteria. Here's a straightforward implementation:
Basic Query Example
Assuming your table is named loans with columns borrower_name (for the borrower's name) and loan_date (for the loan's date), your query would look like this:
SELECT borrower_name, loan_date, [other_columns_you_need] FROM loans ORDER BY borrower_name ASC, loan_date DESC;
Breakdown of the Logic:
ORDER BY borrower_name ASC: This sorts results alphabetically (A-Z) by the borrower's name.ASCis optional here (ascending order is the default), but including it makes your intent explicit for anyone reading the code later.loan_date DESC: For entries with the same borrower name, this sorts by loan date in descending order—so the most recent dates appear first.
Adapting to Your Database Schema
If your table or column names differ (e.g., borrowers instead of loans, full_name instead of borrower_name), just swap those out to match your actual structure. For example:
SELECT full_name, loan_date, loan_amount, repayment_status FROM borrowers ORDER BY full_name, loan_date DESC; -- ASC is omitted here but implied for the name column
Sample Output to Illustrate
Suppose your raw data looks like this:
| borrower_name | loan_date | loan_amount |
|---|---|---|
| Alice | 2023-05-10 | 5000 |
| Bob | 2022-11-01 | 3000 |
| Alice | 2024-01-15 | 7000 |
| Charlie | 2023-09-20 | 4000 |
Your query would return results in this order:
| borrower_name | loan_date | loan_amount |
|---|---|---|
| Alice | 2024-01-15 | 7000 |
| Alice | 2023-05-10 | 5000 |
| Bob | 2022-11-01 | 3000 |
| Charlie | 2023-09-20 | 4000 |
Perfectly matching your requirement: alphabetical by name first, then newest dates at the top for each borrower.
内容的提问来源于stack exchange,提问作者HankySpanky

