SQL over子句PARTITION BY

时间:2018-04-17 02:30:51

标签: sql sql-server tsql outer-join window-functions

努力让over partition by子句使用我希望得到总和值的多个表。

实施例: 表1

Uidx as autonumber,
RepNumber int,
TransDT smalldatetime,
ProductNumber int,
Cost money,

表2

Uidx as autonumber,
T1Uidx int,
PaymentAmount money,

Select RepNumber,ProductNumber,
TotalCost = sum(Cost)  OVER (PARTITION BY RepNumber) ,
TotalPayments = IsNull(sum(PaymentAmount),0)  OVER (PARTITION BY RepNumber) 
from Table1 Left outer join
     Table2 on Table2.T1Uidx = Table1.Uidx
Where TransDT between '3/1/2018' and '3/31/2018'

'一旦我将Left outer Join添加到查询中,就需要FOREVER! '我检查了索引 '我确实有一些空值(我可以在付款字段周围使用isnull) '表大小表1约3200万 '表大小表2约1亿

我希望输出类似于:

RepNumber,ProductNumber,TransDT,TotalCost,TotalPayments
123,999,1/1/2018,50.00,25.00
123,999,1/2/2018,50.00,5.00
456,222,1/4/2018,50.00,40.00
456,333,1/5/2018,50.00,10.00

任何建议都会很棒,。

只要我不包括左外部内部作品如冠军。 但是,只要我包含左外连接,它就会非常慢。 我会给你任何建议。

1 个答案:

答案 0 :(得分:1)

这是您的查询:

Select t1.RepNumber, t1.ProductNumber,
       sum(t1.Cost)  OVER (PARTITION BY t1.RepNumber) as TotalCost, 
       IsNull(sum(t2.PaymentAmount)  OVER (PARTITION BY t1.RepNumber), 0) as TotalPayments
from Table1 t1 Left outer join
     Table2 t2
     on t2.T1Uidx = t1.Uidx
Where t1.TransDT between '2018-03-01' and '2018-03-31';

您正在生成大量行,因此查询速度很慢并不奇怪。

您可以尝试索引:table1(TransDT, Uix, RepNumber, ProductNumber, cost)table2(T1Uidx, PamentAmount)。这些是覆盖索引,可能有助于查询。