2013-05-29 33 views
-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)獲取唯一值。所以,我上面顯示的每一行,會出現所謂的「說明」另一場是會從表C返回:

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 
+0

是什麼TableC中的字段。如果他們有Barrier和Action字段,則可以將其添加到您的聯接中。 – arunlalam

+0

他們做的!對不起,我忘了提到這一點。我怎樣才能加入? – rjbogz

+1

!!! http://stackoverflow.com/q/16819768/1699210 – bummi

回答

1

你加入你的屏障/動作查詢結果表中持有遞減領域。

基本上有兩種語法選項可以選擇。

您可以將屏障/操作查詢放在底部,您可以考慮使用「嵌套查詢」。以下是使用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; 
+0

謝謝!昨天過了幾個小時後,我終於搞清楚了,但在我的工作中如此沉浸其中。這正是我最終做的! :-) – rjbogz