Sql server 基于返回的行运行子查询
我当前正在运行查询:Sql server 基于返回的行运行子查询,sql-server,subquery,Sql Server,Subquery,我当前正在运行查询: select table1.columnA as Barrier_1, table2.columnB as Action_1, from table2 join table1 on table2.PrimKey = table1.PrimKey where table1.columnA is not null and table2.columnB is not null group by table1.columnA, table2.colu
select table1.columnA as Barrier_1,
table2.columnB as Action_1,
from table2
join table1 on table2.PrimKey = table1.PrimKey
where table1.columnA is not null
and table2.columnB is not null
group by table1.columnA, table2.columnB
order by table1.columnA
返回以下表格:
Barrier_1 Action_1
____________________
01 | 01
01 | 02
02 | 01
02 | 03
02 | 04
03 | 02
03 | 03
04 | 01
05 | 04
我还想运行一个子查询,我不知道该怎么做。我需要利用屏障代码和动作代码从另一个表(tableC)中获取唯一的值。因此,对于我上面显示的每一行,将有另一个名为“Desc”的字段,它从tableC返回:
Barrier_1 Action_1 Desc
______________________________
01 | 01 | 15
01 | 02 | 21
02 | 01 | 17
02 | 03 | 12
02 | 04 | 19
03 | 02 | 26
03 | 03 | 13
04 | 01 | 22
05 | 04 | 14
将屏障/动作查询的结果与包含desc字段的表相关联 基本上有两种语法选项可供选择
您可以将Base/Actuple查询放在底部,您可以考虑“嵌套查询”,这是使用AdvyWorkWorksStudio数据库嵌套查询的示例。
SELECT C.ContactID
,C.EmployeeID
,D.[AddressID]
FROM [HumanResources].[EmployeeAddress] D
INNER JOIN ( SELECT A.[ContactID]
,B.EmployeeID
FROM [Person].[Contact] A
INNER JOIN [HumanResources].[Employee] B
ON A.[ContactID] = B.[ContactID] ) C
ON C.EmployeeID = D.EmployeeID;
或者将屏障/动作查询放在顶部,称为“公共表表达式”,此语法风格中的前一个示例如下所示:
WITH T1 ( ContactID, EmployeeID )
AS ( SELECT A.[ContactID]
,B.EmployeeID
FROM [Person].[Contact] A
INNER JOIN [HumanResources].[Employee] B
ON A.[ContactID] = B.[ContactID])
SELECT T1.ContactID
,T1.EmployeeID
,T2.AddressID
FROM T1
INNER JOIN [HumanResources].[EmployeeAddress] T2
ON T1.EmployeeID = T2.EmployeeID;
表C中的字段是什么。如果他们有障碍和行动字段,你可以将其添加到你的加入。他们有!对不起,我忘了提那件事。我怎么才能加入呢?!!!两个独立的问题:-/我知道如何进行连接,因为我在上面使用了它。我想我只是不知道当它有多块的时候该怎么做。谢谢!昨天几个小时后我终于弄明白了,但我还是全神贯注于工作。这正是我最终要做的事情!:-)