Monday, 18 June 2012

Lesson 10: Ordering Multiple Columns in SQL



When ordering your data, you can have multiple sort levels. For example, you can order your data by city and then by name within the city.



Syntax:
Select fieldname, fieldname, fieldname
from tablename
order by fieldname <desc>, fieldname <desc>, fieldname <desc>


Explanation:
  • By default, the Order By clause orders the specified fields in ascending order.
  • Typing "desc" after a field name in the Order By clause tells SQL you want the data in the specified field displayed in descending order (Z to A, 100 to 1).
  • The first field name specified is the primary sort order, the second field name specified is the secondary sort order, and so on ...
Example:Retrieve the city, name, and vendor ID from the TrnVendor table. Order your data by city and then by name within city:
  1. In the SQL text box, type:
Select City, Name, VendId
from TrnVendor
order by City, Name;
  1. Execute the SQL statement.
Results
 

CityNameVendId
BayshoreBayshore ConsultingTV019
BurlingtonBayCon GroupTV020
ChicagoBedMakers LinenTV003
ChicagoDistant HorizonsTV028
ChicagoMake Shift TiltsTV030
ChicagoMusic MakerTV016
ChicagoPaltry PlayTV029
DallasClampett OilTV026

No comments:

Post a Comment