Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.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查询_Sql_Sql Server_Tsql_Window Functions - Fatal编程技术网

试着让我的思维围绕糟糕的SQL查询

试着让我的思维围绕糟糕的SQL查询,sql,sql-server,tsql,window-functions,Sql,Sql Server,Tsql,Window Functions,有人能帮我理解这个查询到底是做什么的吗 SELECT pp.Sedol ,MAX(MAX(Id)) OVER ( PARTITION BY pp.Sedol ,MAX(pp.ValueDate) ) PriceId FROM Prices pp GROUP BY pp.Sedol 这相当于: with x as ( select Sedol, max(id) max_id, Max(ValueDate) max

有人能帮我理解这个查询到底是做什么的吗

SELECT pp.Sedol
    ,MAX(MAX(Id)) OVER (
        PARTITION BY pp.Sedol
        ,MAX(pp.ValueDate)
        ) PriceId
FROM Prices pp
GROUP BY pp.Sedol
这相当于:

with x as (
  select
    Sedol,
    max(id) max_id,
    Max(ValueDate) max_valuedate
  from
    Prices
  group by
    Sedol
) select
  Sedol,
  max(max_id) over (partition by Sedol, max_valuedate) PriceId
from
  x;
尽管正如拉马克所说,我看不出这有什么不等同于

SELECT Sedol, MAX(Id) PriceId FROM Prices GROUP BY Sedol

我认为拉马克已经解释了sql,我正在发布一个示例以供理解。 您可以看到两个SQL都给出了相同的结果。在sql server中复制粘贴下面的代码,然后重试:

declare @Prices table (Id int, ValueDate datetime, Sedol int)

Insert into @Prices values (1,'2014-09-06' ,200),
(2,'2014-09-07' , 100),
(3,'2014-09-08' , 100),
(4,'2014-09-09' , 100),
(5,'2014-09-10' , 300),
(6,'2014-09-11' , 300),
(7,'2014-09-12' , 100),
(8,'2014-09-13' , 200),
(9,'2014-09-14' , 200),
(10,'2014-09-15' , 200)

Select * from @Prices

-- Your SQL
SELECT pp.Sedol
    ,MAX(MAX(Id)) OVER (
        PARTITION BY pp.Sedol
        ,MAX(pp.ValueDate)
        ) PriceId
FROM @Prices pp
GROUP BY pp.Sedol

-- Simple SQL mentioned by Lamak
SELECT Sedol, MAX(Id) PriceId FROM @Prices GROUP BY Sedol
结果集:


不能在聚合函数中进行聚合。这会引发语法错误。很遗憾,它不会。我没有写这篇文章,我只是想了解它应该做什么。@JaazCole:“你不能在一个聚合函数中进行聚合。”,至少如果你使用的是一个窗口函数。我认为这会做同样的事情,那就是
通过Sedol从Prices组中选择Sedol,MAX(Id)PriceId
。第二个
MAX
似乎来自对如何做这件事的误解。而@JaazCole,这实际上不会抛出语法error@Lamak那么分区中的MAX(pp.ValueDate)子句实际上什么都不做?