Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL中的子查询间通信_Sql_Sql Server_Subquery - Fatal编程技术网

SQL中的子查询间通信

SQL中的子查询间通信,sql,sql-server,subquery,Sql,Sql Server,Subquery,我试图找出是否存在任何机制,通过该机制,您可以直接在大型查询中的两个子查询之间传递一些数据,如下所示: select CustomerID, (select PostalCode from Customers where ContactName = S2.ContactName) from Customers where ContactName in (select ContactName from Customers where City = '

我试图找出是否存在任何机制,通过该机制,您可以直接在大型查询中的两个子查询之间传递一些数据,如下所示:

select CustomerID, (select PostalCode from Customers where ContactName = S2.ContactName)
from Customers
where ContactName in (select ContactName
                        from Customers where City = 'London') S2
我想在第一个子查询中使用S2中的数据


注意:上面的查询不应该返回任何有意义的内容,我的查询只是关于SQL子查询是如何工作的。

您可以使用cte,对于内部查询,在出现多LPLE结果的情况下使用agrgation

with cte as
(
select ContactName
 from Customers where City = 'London'
)
select CustomerID, 
(select max(PostalCode) from Customers where ContactName = c1.ContactName
)
from Customers c
join cte c1 on c.ContactName=c1.ContactName

您可以使用cte,对于内部查询,在出现多重查询结果的情况下使用聚合

with cte as
(
select ContactName
 from Customers where City = 'London'
)
select CustomerID, 
(select max(PostalCode) from Customers where ContactName = c1.ContactName
)
from Customers c
join cte c1 on c.ContactName=c1.ContactName

您可以使用窗口功能:

select CustomerID,
       max(case when City = 'London' then PostalCode end) over (partition by ContactName) as london_postalcode
from Customers
where ContactName in (select ContactName
                      from Customers
                      where City = 'London'
                     ) ;

您可以使用窗口功能:

select CustomerID,
       max(case when City = 'London' then PostalCode end) over (partition by ContactName) as london_postalcode
from Customers
where ContactName in (select ContactName
                      from Customers
                      where City = 'London'
                     ) ;

请提供样本数据和预期结果。毫无疑问,有一些直接的方法来做你想做的事;不清楚的是您想要什么。问题是sql server如何在子查询之间传递数据,而不是如何实现某些目标请提供示例数据和所需结果。毫无疑问,有一些直接的方法来做你想做的事;不清楚的是您想要什么。问题是sql server如何在子查询之间传递数据,而不是如何实现某些目标