SQL Server在子查询中重用别名
这听起来像是一个愚蠢的问题-抱歉,我是SQL Server新手,我只想确认我的理解。 我有一个查询,它以不同的方式将表中的值聚合为不同列的子查询,例如,对于给定日期的事务、前一个月的事务、前6个月的事务、之前的事务、之后的事务 我将主表别名为SQL Server在子查询中重用别名,sql,sql-server,tsql,sql-server-2012,Sql,Sql Server,Tsql,Sql Server 2012,这听起来像是一个愚蠢的问题-抱歉,我是SQL Server新手,我只想确认我的理解。 我有一个查询,它以不同的方式将表中的值聚合为不同列的子查询,例如,对于给定日期的事务、前一个月的事务、前6个月的事务、之前的事务、之后的事务 我将主表别名为tx,然后子查询别名为tx1,因此可以使用以下示例: tx1.TransactionDate < tx.TransactionDate 我认为下面的脚本可以解释一切 SELECT 1,1,GETDATE() INSERT INTO @t ( Id,
tx
,然后子查询别名为tx1
,因此可以使用以下示例:
tx1.TransactionDate < tx.TransactionDate
我认为下面的脚本可以解释一切
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*/
这意味着是的,它可以被重用,但只有当您不想比较main/sub时,因为如果您重用它,例如,您尝试在subquery
tx.Id>tx.Id
中执行以下语句,则只会比较子查询中的值。在我们的示例中,这会导致您得不到任何结果,因为您将值放在同一行中…问题中的Post代码。我已经编辑了你的问题。以下是一篇相关文章,可以帮助您:
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*/