2017-11-11 228 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

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