【问题标题】:SQL Server reuse aliases in subqueriesSQL Server 在子查询中重用别名
【发布时间】:2016-10-28 21:46:50
【问题描述】:

这听起来像是一个愚蠢的问题 - 抱歉,我是 SQL Server 的新手,我只是想确认我的理解。 我有一个查询,它以不同的方式将表中的值聚合为子查询,用于不同的列,例如对于给定日期的交易,上个月、前 6 个月、之前、之后的交易。

我将主表别名为tx,然后将子查询别名为tx1,因此我可以使用例如:

tx1.TransactionDate < tx.TransactionDate

我创建了一列,复制它并修改了WHERE 条件。

我假设子查询中别名的范围绑定到该子查询,因此在每种情况下别名是否相同并不重要。

它似乎有效,但是由于主表 tx 和子查询表 tx1 都没有改变,我不知道别名 tx1 的范围是否绑定到每个子查询,或者初始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]

【问题讨论】:

标签: sql sql-server tsql sql-server-2012


【解决方案1】:

我认为下面的脚本可以解释一切。

SELECT 1,1,GETDATE()
INSERT INTO @t ( Id, UserId, TranDate )
SELECT 2,1,GETDATE()
INSERT INTO @t ( Id, UserId, TranDate )
SELECT 3,1,GETDATE()



SELECT tx.Id/*main alias*/,
       tx1.Id /*First subquery alias*/,
       tx2.Id /*Second subquery alias*/,
       (SELECT Id FROM @t txs /*alias only in this one subquery/must be different from main if you want use main alias in it...*/ 
        WHERE txs.Id = tx.Id+2 /*here is used main value = subquery value+2*/) AS Id
FROM @t tx /*main*/
JOIN (SELECT * 
      FROM @t tx 
      WHERE tx.Id =  1 /*this one using subquery values + you are not able to use here main value*/ 
      ) tx1 --alias of subquery
      ON tx.Id = tx1.Id /*here is used main value = subquery value*/
CROSS APPLY (SELECT TOP 1 * 
             FROM @t txc /*This one must be different from main if you want use it to comparison with main*/
             WHERE txc.Id > tx.Id /*this one using subquery value > main value*/ 
             ) tx2 --alias of subquery
WHERE tx.Id = 1 AND /*Subquery alias canot reference on First subquery value*/
      tx1.Id = 1 AND/*Subquery alias*/
      tx2.Id = 2 /*Subquery alias*/

这意味着是的,它可以被重用,但前提是你不想比较主/子,因为如果你重用它,例如你尝试在子查询中执行以下语句tx.Id &gt; tx.Id它会导致只有子查询中的值将进行比较。在我们的示例中,它会导致您没有得到任何东西,因为您将值放在同一行中......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多