简体   繁体   English

SQL Server将表联接到自身而不是在子查询中作为选择的效率

[英]SQL server efficiency of joining a table to itself rather than as a select in a subquery

This might sound like a dumb question - apologies if this has been answered before (almost certainly) but I couldn't find an answer with search. 这听起来像是一个愚蠢的问题-很抱歉,如果之前(几乎可以肯定)回答了这个问题,但我找不到搜索的答案。

I've got a query that is aggregating values in a table as a subquery in different ways for different columns, eg for a transaction on a given day, transactions in the previous month, previous 6 months, before that, after that. 我有一个查询,它以不同方式将表中的值作为子查询聚合为不同的列,例如对于给定日期的交易,上个月,前6个月的交易,然后是之后的交易。 I aliased the main table as tx, then the subquery alias as tx1 我将主表别名为tx,然后将子查询别名别名为tx1

SELECT 
    tr.transaction_value
    ,ISNULL(
         (SELECT SUM(tr1.transaction_value) FROM [MyDB].[dbo].[Transactions] tr1
         WHERE tr1.Client_Ref = tr.Client_Ref),0) AND tr1.Transaction_Date > tr.Transaction_Date 
     ),0) as 'Future_Transactions'
    ,ISNULL(
         (SELECT SUM(tr1.transaction_value) FROM [MyDB].[dbo].[Transactions] tr1
         WHERE tr1.Client_Ref = tr.Client_Ref),0) AND tr1.Transaction_Date < tr.Transaction_Date 
     ),0) as 'Prior_Transactions'
FROM [MyDB].[dbo].[Transactions] tr 

I want to know, if I have 7 such columns with subqueries, defining the table 7 times in the subqueries, is it possible and better (more efficient, more readable) to create tx1 as an INNER JOIN on the main table query rather than recreating it in each subquery, and if so how would I code the WHERE clauses? 我想知道,如果我有7个带有子查询的列,在子查询中定义了7次表,是否有可能(在重新创建时)在主表查询中将tx1创建为INNER JOIN(更高效,更易读),而不是重新创建它在每个子查询中,如果是的话,我该如何编码WHERE子句? Thanks :o) 谢谢:o)

This should be equivalent and better performing. 这应该是等效的并且性能更好。

SELECT 
    tr.transaction_value
    ,SUM(tr1.transaction_value) as 'Future_Transactions'
    ,SUM(tr2.transaction_value) as 'Prior_Transactions'
FROM [MyDB].[dbo].[Transactions] tr
LEFT JOIN [MyDB].[dbo].[Transactions] tr1 ON tr1.Client_Ref = tr.Client_Ref AND tr1.Transaction_Date > tr.Transaction_Date 
LEFT JOIN [MyDB].[dbo].[Transactions] tr2 ON tr2.Client_Ref = tr.Client_Ref AND tr2.Transaction_Date < tr.Transaction_Date 
group by tr.transaction_value

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

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