在没有聚合函数的情况下进行分区,避免分组

over partition by without an aggregate function, avoiding group by

有什么方法可以像 over (partition by column) 一样使用 window 函数而不将其用作聚合函数?

我有很多列,我不想使用 group by 因为我必须在 select 和组中指定通过.

我给出了一个语法示例,它需要以某种方式进行更正(你们是因为当我在我的真实查询中调整它时它不起作用(真实查询太长和费时来解释它所以只是继续一个例子)).

让我们假设这行得通:

select *,
( select
sum (column1) over (partition by column2) as sumCol1
from myTable
where column20 = column21
)
from myTable

好的,现在我想做同样的事情,但有两个变化:

1: 无聚合函数

2: column1 这次将是 DATE (我无法将聚合函数与 date 据我所知,但由于我正在尝试消除聚合,所以这无关紧要。)

我想要的应该是这样的(查询不正确,因为这是我想要实现的)

  select *,
    ( select
    column1 over (partition by column2) as Col1New
    from myTable
    where column20 = column21
    )
    from myTable

SQL 服务器 2012

谢谢

编辑:

示例数据:

     rN         rD          rnc      d     e   name  
    abc1m      2010-03-31   abc     5.7    2   blue   
    abc3m      2010-04-15   abc     5.7    3   blue  
    abc1y      2010-02-14   abc     5.7    4   blue   
    xfx1m      2010-02-31   xfx     1.7    2   blue  
    xfx3m      2010-03-24   xfx     1.7    1   blue  
    xfx1y      2012-03-30   xfx     1.7    1.7 red    <= d=e use this date for "red" rows
    tnt1m      2010-03-28   tnt     9.6    2   red   
    tnt3m      2010-01-12   tnt     9.6    9.6 blue   <= d=e use this date for "blue" rows
    tnt1y      2010-08-20   tnt     9.6    2   red 

预计table,请看expectedCol

rN         rD          rnc      d     e   name  expectedCol
abc1m      2010-03-31   abc     5.7    2   blue  2010-01-12 
abc3m      2010-04-15   abc     5.7    3   blue  2010-01-12 
abc1y      2010-02-14   abc     5.7    4   blue  2010-01-12 
xfx1m      2010-02-31   xfx     1.7    2   blue  2010-01-12 
xfx3m      2010-03-24   xfx     1.7    1   blue  2010-01-12 
xfx1y      2012-03-30   xfx     1.7    1.7 red   2012-03-30 
tnt1m      2010-03-28   tnt     9.6    2   red   2012-03-30 
tnt3m      2010-01-12   tnt     9.6    9.6 blue  2010-01-12 
tnt1y      2010-08-20   tnt     9.6    2   red   2012-03-30 

逻辑是这样的:当 d = e 然后查看 rD 并获取该日期并将其按名称放入 expectedCol1 组中

所以,我想写这样的东西:

select *,
(select rD over (partition by name) as expectedCol1
from myTable
where d = e)
from myTable

只需计算每个 namerD,其中 d = e

WITH myDate AS ( 
      SELECT name, rD
      FROM YourTable
      WHERE d = e
)
SELECT
       t.*, m.rD as expectedCol           
FROM YourTable t
JOIN myDate m
  ON t.name = m.name

根据您的样本数据,像这样更简单的东西看起来应该可行:

select t1.*,t2.rD as expectedCol1
from myTable t1
inner join (select name,rD from myTable where e = d) t2
on t1.name = t2.name

由于您已经声明 e=d 组合对于每个名称只出现一次,因此 t2 子查询应该为每个名称包含一行。如果某些名称可能没有任何 e=d 的行,如果您希望将它们包括在内,则应更改为 left join,然后考虑在这种情况下 expectedCol1 应该是什么。

正如我在评论中提到的那样,第三种方法是使用简单的子查询:

SELECT t.*, (
  SELECT rD FROM myTable t2 WHERE t2.e=t2.d AND t2.Name=t.Name
) AS ExpectedCol
FROM myTable t