Quick question. I'm running through an SQL challenge and it seems to me that using an Alias works in some instances, but not in others. It seems arbitrary, but I know I'm missing something.
Consider Code A:
Select DOW = datename(dw, orderdate), Revenue = sum(subtotal), Orders = count(*), RPO = sum(subtotal) from sales.salesorderheader
where year(orderdate) = 2008
and OnlineOrderFlag = 0
Group by datename(dw, orderdate)
Order by RPO desc
That works just fine. I like that in the Order by part of the code, I can refer to sum(subtotal) by the Alias Revenue.
If I try to do the same with the Group By line, it doesn't work. I.e. the following doesn't work:
Select DOW = datename(dw, orderdate), Revenue = sum(subtotal), Orders = count(*), RPO = sum(subtotal) from sales.salesorderheader
where year(orderdate) = 2008
and OnlineOrderFlag = 0
Group by DOW
Order by RPO desc
Why can I use the alias with the Order by clause, but not hte Group by clause? I'm forced to type out the full "Group by datename(dw, orderdate)"
Thanks!
group byclause gets processed before theselectclause.