2017-11-11 267 views
1

我有一個查詢,我試圖解決但無法做到這一點。SQL Server 2012數據庫查詢問題

以下是需要評估的查詢。

Declare @Table Table(SSYId INT, Name VARCHAR(100), Address VARCHAR(100), ParentSSYId INT, RelationWithParentSSY VARCHAR(50)) 
INSERT INTO @Table VALUES (1,'A','Maninagar, Ahmedabad',2,'Wife') 
INSERT INTO @Table VALUES (2,'B','Maninagar, Ahmedabad',NULL,NULL) 
INSERT INTO @Table VALUES (3,'C','Isanpur, Ahmedabad',NULL,NULL) 
INSERT INTO @Table VALUES (4,'D','Isanpur, Ahmedabad',3,'Husband') 
INSERT INTO @Table VALUES (5,'E','Gokuldham, Ahmedabad',NULL,NULL) 

那麼結果將是

SSYId | Name | Address     | ParentSSYId | RelationWithParentSSY 
1  | 'A' | 'Maninagar, Ahmedabad' | 2    | 'Wife' 
2  | 'B' | 'Maninagar, Ahmedabad' | NULL   | NULL 
3  | 'C' | 'Isanpur, Ahmedabad'  | NULL   | NULL 
4  | 'D' | 'Isanpur, Ahmedabad'  | 3    | 'Husband' 
5  | 'E' | 'Gokuldham, Ahmedabad' | NULL   | NULL 

在這裏,我已經證明原始數據,其中關係,地址在我的分貝我已經創建外鍵varchar字段。預期結果如下。

PrimaryName | SecondaryName | Address 
A    | B    | 'Maninagar, Ahmedabad' 
C    | D    | 'Isanpur, Ahmedabad' 
E    | NULL    | 'Gokuldham, Ahmedabad' 

在結果中你可以看到丈夫的名字應該出現在PrimaryName中,而妻子的名字應該出現在SecondaryName中。如果沒有任何其他關係指定,那麼只有它顯示在PrimaryName和SecondaryName中應該爲空或爲空。

我試着得到預期的結果。

SELECT DISTINCT STUFF((SELECT ',' + T2.Name FROM @Table T2 WHERE T2.ParentSSYId = T.SSYId ORDER BY T2.SSYId FOR XML PATH('')),1,1,'') AS PrimaryName, 
T1.Name AS SecondaryName, 
T1.Address AS Address 
FROM @Table T 
INNER JOIN @Table T1 
ON T.SSYId = T1.ParentSSYId 
GROUP BY T.SSYId,T.Name,T.ParentSSYId,T.Address     

在上面的查詢中,我不知道如何檢查它是丈夫還是妻子,所以我必須把它放在第一列。

您的幫助將不勝感激。

預先感謝您。

Nikunj

+0

請嘗試寫一個實際描述你的問題的標題。 「事X問題」沒有用,會阻止人們點擊閱讀你的問題。 –

回答

2

我想你基本上只需要一個case聲明:

select (case when tparent.SSYId is null or tparent.RelationWithParentSSY = 'wife' 
      then t.Name 
      else tparent.Name 
     end) as PrimaryName, 
     (case when tparent.SSYId is null or tparent.RelationWithParentSSY = 'wife' 
      then tparent.Name 
      else t.Name 
     end) as SecondaryName 
     t.address 
from @Table t left join 
    @Table tparent 
    on t.SSYId = tparent.ParentSSYId 
where t.ParentSSYId is null; 

事實上,你可能會發現邏輯中的 「老公」 方面更清晰:

select (case when tparent.RelationWithParentSSY = 'husband' 
      then tparent.Name 
      else t.Name 
     end) as PrimaryName, 
     (case when tparent.RelationWithParentSSY = 'husband' 
      then t.Name 
      else tparent.Name 
     end) as SecondaryName 
     t.address 
from @Table t left join 
    @Table tparent 
    on t.SSYId = tparent.ParentSSYId 
where t.ParentSSYId is null 
+0

你真的很棒@戈登。我只是在等待你的回覆。太好了..!! –