-1

我目前运行查询:

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
4

1 回答 1

1

您将障碍/操作查询的结果加入到包含 desc 字段的表中。

基本上有两种语法选项可供您选择。

您可以将障碍/操作查询放在底部,您可以将其视为“嵌套查询”,这是使用 AdventureWorks 示例数据库的嵌套查询示例。

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;
于 2013-05-30T03:07:52.043 回答