2017-08-30 74 views
0

我需要使用連接或通過其他方式從表中的兩行中取出單行。我有三個表Account,Account_Perm和User。帳戶表具有一個名爲AccountNum的字段,Account_Perm具有AccountNum,TeamRole和UserName的字段,用戶表具有用戶名。示例數據如下。在SQL Server中連接從表的兩行中獲取單行

  • 帳戶==> AccountNum = 1234,5678
  • Account_Perm ==> AccountNum = 1234,TeamRole = TeamA; AccountNum = 1234,TeamRole = TeamB
  • User ==> TeamRole = TeamA,UserName = John Smith; TeamRole = TeamB,UserName =「凱西布朗」。

我需要使用這些表和我的結果集與列(AccountNum,TeamRole,TeamRole)應該如下。

1234, John Smith, Casey Brown 

通過使用加入,我能得到兩行,1234,約翰·史密斯和1234,凱西·布朗。不過,我需要AccountNum,TeamA的用戶名和TeamB的用戶名單獨記錄。

有人可以幫忙嗎?

查詢:

SELECT 
    A.AccountNum, 
    A.TeamRole, 
    U.Name 
FROM 
    Account A, 
    Account_Perm AA, 
    User U 
WHERE 
    A.AccountNum = AA.AccountNum 
    AND AA.TeamRole IN ('TeamA', 'TeamB') 
    AND AA.UserName = U.Name; 
+0

'使用Join' ......請註明您目前的查詢。您的數據非常難以閱讀和理解。 –

+0


選擇A.AccountNum,A.TeamRole,U.Name 從賬戶A,Account_Perm AA,用戶u WHERE \t A.AccountNum = AA.AccountNum AND \t \t AA.TeamRole IN( 'TeamA', 'TeamB' ) AND \t \t AA.UserName = U.Name –

+2

您的數據和問題不清楚,甚至我甚至無法猜測答案。執行以下操作:_編輯_問題以表格形式顯示示例數據,就像SQL查詢返回一樣,然後2)用示例結果顯示示例輸出表。你應該意識到,如果你一開始就這樣做了,你可能已經有了答案。 –

回答

0
declare @Account table(AccountNum int); 
insert into @Account values (1234), (5678); 

declare @Account_Perm table (AccountNum int, TeamRole varchar(100)) 
insert into @Account_Perm values(1234, 'TeamA'), (1234, 'TeamB'); 

declare @User table (TeamRole varchar(100), UserName varchar(100)); 
insert into @User values ('TeamA', 'John Smith'), ('TeamB','Casey Brown'); 

--AccountNum, TeamRole, TeamRole) should be as below. 
--1234, John Smith, Casey Brown 
with cte AS 
(
SELECT 
    A.AccountNum, 
    AA.TeamRole, 
    U.UserName 
FROM 
    @Account A join @Account_Perm AA 
     on A.AccountNum = AA.AccountNum 
    join @User U 
     on AA.TeamRole = U.TeamRole 
WHERE AA.TeamRole IN ('TeamA', 'TeamB') 
) 

select * 
from cte pivot(max(UserName) for TeamRole in ([TeamA], [TeamB]))p 
+0

你的解決方案似乎很好。謝謝你的幫助。一件小事。如果某個帳戶沒有TeamA的行,則與TeamA對應的用戶名將填充爲NULL。有沒有辦法讓它變成空白? –

+0

沒關係。我通過將ISNULL子句添加到select中來實現它。 –

相關問題