Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在sql server中,为什么在比较两个表中的数据时不能使用函数_Sql_Sql Server_Max - Fatal编程技术网

在sql server中,为什么在比较两个表中的数据时不能使用函数

在sql server中,为什么在比较两个表中的数据时不能使用函数,sql,sql-server,max,Sql,Sql Server,Max,有人能告诉我下面的问题是什么吗 select 1 from table1 a, table2 b where a.pdate=max(b.pdate) 它没有被编译 编写此查询的另一种方法是 set @pdate=pdate from table2 select 1 from table1 a, table2 b where a.pdate=max(b.pdate) 但我想了解第一个查询有什么问题 谢谢即使第二个查询也是错误的 正确的方式, Select @pdate=max(pd

有人能告诉我下面的问题是什么吗

select 1 
from table1 a, 
table2 b 
where a.pdate=max(b.pdate)
它没有被编译

编写此查询的另一种方法是

set @pdate=pdate from table2
select 1 
from table1 a, 
table2 b
where a.pdate=max(b.pdate)
但我想了解第一个查询有什么问题


谢谢

即使第二个查询也是错误的

正确的方式,

Select @pdate=max(pdate) from table2

select 1 
from table1 a where a.pdate=@pdate
或者

如果您提到了聚合列之外的另一个列名,则必须使用group by

但我想了解第一个查询有什么问题

错误消息告诉您一些可能对您有价值的信息

除非是在一个集合中,否则集合不能出现在WHERE子句中 HAVING子句或select列表中包含的子查询,以及列 聚合是一个外部引用

max()
函数是一个聚合,返回一组行的最大值。where子句用于筛选行。因此,如果在进行过滤的位置使用聚合,则不清楚实际需要最大值的行

重写可能如下所示:

select 1 
from dbo.table1 as a 
where a.pdate = (
                select max(b.pdate)
                from dbo.table2 as b
                );

在where子句中不能使用max。。。参考此
select 1 
from dbo.table1 as a 
where a.pdate = (
                select max(b.pdate)
                from dbo.table2 as b
                );