【发布时间】:2016-01-27 02:02:50
【问题描述】:
有什么方法可以使用像 over (partition by column) 这样的窗口函数而不将其用作聚合函数?
我有很多列,我不想使用 group by,因为我必须在 select 和 group by 中都指定。
我正在给出一个语法示例,需要以某种方式进行更正(你们会导致当我在我的实际查询中调整它时它不起作用(实际查询太长而且解释它太费时,所以只需举个例子))。
假设这是可行的:
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 Server 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
预期表,请看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
【问题讨论】:
-
你能提供样本数据和期望的输出吗?这会有很大帮助。
-
你可以随时使用聚合函数
MAX() -
你真的需要数据样本来回答吗:
is it possible to use partition by without an aggregate function? -
是的@CM2K,因为您的问题不清楚,并且不确定您要达到什么目的。我可以尝试猜测。但可能会浪费我的时间。
-
看起来您最好使用 CASE 语句或子查询获取
expectedCol。
标签: sql sql-server tsql sql-server-2012 window-functions