集合操作中别名的使用问题
use Northwind
go
select EmployeeID ,CustomerID,OrderID,OrderDate
from ( select 1 as SortCol,CustomerID,EmployeeID,OrderID,OrderDate
from dbo.Orders
where CustomerID = 'ALFKI'
union all
select 2 as SortCol,CustomerID,EmployeeID,OrderID,OrderDate
from dbo.Orders
where EmployeeID = 3 )as U
order by SortCol ,
case when SortCol = 1 then OrderID end,
case when SortCol = 2 then OrderDate end desc;
上面的sql语句使用示例数据库Northwind中的表Orders,当CustomerID
为ALFKI,按OrderID排当EmployeeID = 3按 OrderDate降序排这儿为什么
去掉集合操作中的别名as U会报错????
------最佳解决方案--------------------from 后面接表名或者子查询名称.你把 as U去掉后,就没有名称了.当然会报错.
------其他解决方案--------------------因为 (select 1 as SortCol,CustomerID,EmployeeID,OrderID,OrderDate
from dbo.Orders
where CustomerID = 'ALFKI'
union all
select 2 as SortCol,CustomerID,EmployeeID,OrderID,OrderDate
from dbo.Orders
where EmployeeID = 3 ) 整个 作为了一个名为U的表来使用
简写就是
select EmployeeID ,CustomerID,OrderID,OrderDate from U order by SortCol ,
case when SortCol = 1 then OrderID end,
case when SortCol = 2 then OrderDate end desc;
------其他解决方案--------------------楼上回答的我知道,现在如果不使用别名U,也就是去掉as U, 就会报错,这个是怎么回事????