按列别名对PagedTable进行排序

时间:2014-04-25 01:28:19

标签: sql sorting

是否可以通过列别名之一对PagedTable的结果进行排序?

这是我的工作查询:

SELECT * FROM 
( 
SELECT 
DI.P_ID as IDEA_ID, 
DI.P_IDEA_NUMBER as IDEA_NUMBER, 
CASE WHEN len(DI.P_TITLE) < 1 then 'None recorded' else DI.P_TITLE END as IDEA_TITLE, 
CASE WHEN len(DI.P_IDEA_MANAGER) < 1 then 'None' ELSE isnull((Select top 1 FName+' 'LName from OTHERSERVER.OTHERDB.dbo.Usernames as UN1 where (XID=DI.P_IDEA_MANAGER) order by endDate desc),'No longer on record') end as IDEA_MANAGER, 
CASE WHEN len(DI.P_RELEASE_MONTH) < 1 or len(DI.P_RELEASE_YEAR) < 1 then 'None recorded' else DI.P_RELEASE_MONTH+'/'+DI.P_RELEASE_YEAR END as IDEA_REQUESTED_RELEASE, 
SIS.LABEL as IDEA_STATUS, 
ROW_NUMBER() OVER(Order by DI.P_IDEA_NUMBER ASC) as RowNum 
FROM 
DATA_IDEA as DI 
LEFT OUTER JOIN 
SEL_IDEA_STATUS as SIS on SIS.ID=(SELECT TOP 1 S_ID from DATA_IDEA_STATUS as DIS where (DIS.P_ID=DI.P_ID) order by created desc) 
WHERE 
(SIS.IS_DRAFT='True')
) 
as PagedTable where (RowNum between 1 and 10)

有了这个,我按“想法编号”排序结果,即1,2,3等。 而不是按“DI.P_IDEA_NUMBER”排序,是否可以通过“IDEA_NUMBER”排序?

你可能认为这不是一个很大的交易,按想法编号排序。好吧,我还必须通过“IDEA_MANAGER”对结果进行排序。根据案例statemnt,IDEA_MANAGER将是三件事之一。 1)John Smith,2)没有记录,3)不再记录

1 个答案:

答案 0 :(得分:0)

&#34;是否可以通过其中一列别名对PagedTable的结果进行排序?&#34;

你尝试过吗?

这应该有效:

SELECT Col1 AS MyAlias 
  FROM tbl 
 ORDER BY MyAlias 

这也应该有效:

SELECT * 
  FROM (SELECT Col1 AS MyAlias FROM tbl) a
 ORDER BY MyAlias 

但它可能取决于你的RDBMS。

借鉴How do i use alias in where clause?

  

column_alias可以在ORDER BY子句中使用,但不能使用它   在WHERE,GROUP BY或HAVING子句中。

Taken from the MSSQL Doc

此外,您不能将其用作OVER子句。

cannot use alias in ROW_NUMBER() over in SQL Server?