Hi,
I'm a new SAS user. Pls help me understand the difference in the following code.
In the first code - rbc and wbc written right after "BY" statement are sorted in the ascending order.
In the second code - rbc and cholesterol written after wbc is not sorted in ascending order. Why is that?
As per my understanding, variables in "BY" statement are default sorted in ascending order.
PROC SORT DATA = blood OUT = sorted_blood;
BY rbc cholesterol DESCENDING wbc;
run;
PROC SORT DATA = blood OUT = sorted_blood;
BY DESCENDING wbc rbc cholesterol;
run;
As per my understanding, variables in "BY" statement are default sorted in ascending order.
That's correct.
In the second code - rbc and cholesterol written after wbc is not sorted in ascending order. Why is that?
Your sort is: BY DESCENDING wbc rbc cholesterol;
The first level of sorting is: DESCENDING wbc
Within the same value for WBC rows then get sorted by ascending rbc and then within the same value of rbc they get sorted by ascending cholesterol.
To "see" that the sorting also works for 3rd level cholesterol you would need to find multiple rows in your source data with identical values for wbc and rbc.
If you look at your data then you'll see that it's sorted as requested.
As per my understanding, variables in "BY" statement are default sorted in ascending order.
That's correct.
In the second code - rbc and cholesterol written after wbc is not sorted in ascending order. Why is that?
Your sort is: BY DESCENDING wbc rbc cholesterol;
The first level of sorting is: DESCENDING wbc
Within the same value for WBC rows then get sorted by ascending rbc and then within the same value of rbc they get sorted by ascending cholesterol.
To "see" that the sorting also works for 3rd level cholesterol you would need to find multiple rows in your source data with identical values for wbc and rbc.
If you look at your data then you'll see that it's sorted as requested.
All the by variables are sorted in ascending order by default. Variables to be sorted by descending order should be preceded by the word descending, which is what you are doing in your code.
You are sorting the whole table by:
RBC in ascending order
Then, by Cholesterol in Ascending Order.
And finally, by WBC in Descending order due to the keyword 'descending' placed before WBC.
Sort applies to variables in the order listed under BY variable. If you study the rows with identical data points, you will understand.
Second example:
Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.