一条sql语句怎么有错

yung7086 2012-06-05 09:21:53
select *, row_number()over (order by customer) as num from TableA where num>1

这个执行的时候说num不存在

select * from (select *, row_number()over (order by customer)as num from TableA ) a where a.num>1
一般是这样写的,,我问下为什么那样写不可以呢。求指点
...全文
252 7 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qxyywy 2012-06-05
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
select *, row_number()over (order by customer) as num from TableA where num>1

这个执行的时候说num不存在

select * from (select *, row_number()over (order by customer)as num from TableA ) a where a.num>1
一……
[/Quote]

这是开窗函数 上面的几位也都说了原因
另注:开窗函数不能直接跟在where之后 如:
select * from TableA where row_number()over (order by customer)>1

具体的开窗函数使用方法楼主自己搜索吧
EnForGrass 2012-06-05
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

其实很简单,既然是from TableA ,因为TableA 中没有num,所以不存在
[/Quote]

create table employee (empid int ,deptid int ,salary decimal(10,2))
insert into employee values(1,10,5500.00)
insert into employee values(2,10,4500.00)
insert into employee values(3,20,1900.00)
insert into employee values(4,20,4800.00)
insert into employee values(5,40,6500.00)
insert into employee values(6,40,14500.00)
insert into employee values(7,40,44500.00)
insert into employee values(8,50,6500.00)
insert into employee values(9,50,7500.00)

SELECT * FROM employee

SELECT * FROM (SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee) AS newtable WHERE newtable.rank>2
/*
empid deptid salary rank
----------- ----------- --------------------------------------- --------------------
5 40 6500.00 3

(1 行受影响)

*/
麦麦 2012-06-05
  • 打赏
  • 举报
回复
num是别名,并没有存在于TableA中,所以不存在。
EnForGrass 2012-06-05
  • 打赏
  • 举报
回复
其实很简单,既然是from TableA ,因为TableA 中没有num,所以不存在
xiaoning8201 2012-06-05
  • 打赏
  • 举报
回复
select * from (select *,row_number() over(order by CODEID) as my from BASEDETAILMST) as b where my > 0 and my<=1
宝_爸 2012-06-05
  • 打赏
  • 举报
回复
select *, row_number()over (order by customer) as num from TableA where num>1 不行是因为where 在select前面执行,因此select 中的as给的别名, where是不知道的。

参考:
SQL SERVER – Logical Query Processing Phases – Order of Statement Execution
http://blog.sqlauthority.com/2009/04/06/sql-server-logical-query-processing-phases-order-of-statement-execution/


select * from (select *, row_number()over (order by customer)as num from TableA ) a where a.num>1可以是因为括号中的语句执行后,num 已经是一个column name了,因此where 中可以使用
小火龙果 2012-06-05
  • 打赏
  • 举报
回复
自己放sql里面执行一下不就知道哪里错了吗

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧