小编典典

如何合并GROUP BY和ROW_NUMBER?

sql

我希望以下示例代码是不言自明的:

declare @t1 table (ID int,Price money, Name varchar(10))
declare @t2 table (ID int,Orders int,  Name varchar(10))
declare @relation  table (t1ID int,t2ID int)
insert into @t1 values(1, 200, 'AAA');
insert into @t1 values(2, 150, 'BBB');
insert into @t1 values(3, 100, 'CCC');
insert into @t2 values(1,25,'aaa');
insert into @t2 values(2,35,'bbb');
insert into @relation values(1,1);
insert into @relation values(2,1);
insert into @relation values(3,2);

select T2.ID AS T2ID
,T2.Name as T2Name
,T2.Orders
,T1.ID AS T1ID
,T1.Name As T1Name
,T1Sum.Price
FROM @t2 T2
INNER JOIN (
    SELECT Rel.t2ID
        ,MAX(Rel.t1ID)AS t1ID 
-- the MAX returns an arbitrary ID, what i need is: 
--      ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,SUM(Price)AS Price
        FROM @t1 T1 
        INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
        GROUP BY Rel.t2ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID
INNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID

结果:

T2ID   T2Name   Orders  T1ID    T1Name  Price     
 1      aaa       25     2       BBB    350,00     
 2      bbb       35     3       CCC    100,00

我需要的是上述评论的,一种方式来获得的ROW_NUMBER,但也Group By摆在首位。因此,我需要在关系表和外部查询中按最高sum价格分组的所有T1价格。T2.ID``t1ID

换句话说:如何更改MAX(Rel.t1ID)AS t1ID为以最高价格返回ID?

因此,期望的结果是(请注意,由于价格较高,第一个T1ID从2更改为1):

T2ID   T2Name   Orders  T1ID    T1Name  Price     
 1      aaa       25     1       AAA    350,00     
 2      bbb       35     3       CCC    100,00

注意
:如果您想知道为什么我不Orders与Price相乘:它们没有被实现(因此,由于它有点模棱两可,所以我应该省略此列,请忽略它,我只是添加了此内容以减少所有内容抽象的)。实际上Orders必须保持不变,这就是子查询方法将两者都加入的原因,也是我首先需要分组依据的原因。

结论 :很明显,我的问题的核心可以由可应用于 任何
聚合函数的OVER子句回答,这些函数对我来说是新的\


阅读 284

收藏
2021-04-15

共1个答案

小编典典

哇,其他答案看起来很复杂-所以我希望我没有错过任何显而易见的事情。

您可以对聚合使用OVER/ PARTITION BY,然后它们将在没有GROUP BY子句的情况下进行分组/聚合。因此,我刚刚将您的查询修改为:

select T2.ID AS T2ID
    ,T2.Name as T2Name
    ,T2.Orders
    ,T1.ID AS T1ID
    ,T1.Name As T1Name
    ,T1Sum.Price
FROM @t2 T2
INNER JOIN (
    SELECT Rel.t2ID
        ,Rel.t1ID
 --       ,MAX(Rel.t1ID)AS t1ID 
-- the MAX returns an arbitrary ID, what i need is: 
      ,ROW_NUMBER()OVER(Partition By Rel.t2ID Order By Price DESC)As PriceList
        ,SUM(Price)OVER(PARTITION BY Rel.t2ID) AS Price
        FROM @t1 T1 
        INNER JOIN @relation Rel ON Rel.t1ID=T1.ID
--        GROUP BY Rel.t2ID
)AS T1Sum ON  T1Sum.t2ID = T2.ID
INNER JOIN @t1 T1 ON T1Sum.t1ID=T1.ID
where t1Sum.PriceList = 1

给出请求的结果集。

2021-04-15