简体   繁体   English

SQL over子句PARTITION BY

[英]SQL over clause PARTITION BY

Struggling to get the over partition by clause working with multiple tables that I want the sum values from. 努力让over partition by子句与要从中获取和值的多个表一起使用。

Example: Table1 示例:表1

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

Table2 表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'

'Once I add the Left outer Join to the query it takes FOREVER!. “一旦将左外部联接添加到查询中,它将永远需要!! 'I checked the indexs 'I do have some null values (I can use isnull around the payment field) 'Table size Table1 about 32million 'Table size Table2 about 100million '我检查了索引'我确实有一些空值(我可以在付款字段中使用isull)'表大小Table1约为3200万'表大小Table2约为1亿

I would like an output similiar to: 我想要类似的输出:

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

Any suggestion would be great,. 任何建议都很好。

As long as I DO NOT include the left outer inner works like a champ. 只要我不包括左外部的内部作品就如冠军。 However as soon as I include the left outer join it gets very slow. 但是,一旦我包括左外部连接,它就会变得很慢。 I would apperciate any advice you may give. 如果您有任何建议,我将不胜感激。

This is your query: 这是您的查询:

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';

You are generating a lot of rows, so I'm not surprised that the query is slow. 您正在生成很多行,因此对于查询速度很慢并不感到惊讶。

You can try indexes: table1(TransDT, Uix, RepNumber, ProductNumber, cost) and table2(T1Uidx, PamentAmount) . 您可以尝试索引: table1(TransDT, Uix, RepNumber, ProductNumber, cost)table2(T1Uidx, PamentAmount) These are covering indexes and might help the query. 这些涵盖索引,可能有助于查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM