SQL Server 2012数据库查询问题

时间:2017-11-11 11:57:04

标签: sql sql-server 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

这里我展示了原始数据,其中关系和地址是我的db中的varchar字段我创建了外键。预期结果如下所述。

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

在结果中你可以看到丈夫的名字应该在PrimaryName中,而妻子的名字应该在SecondaryName中。如果没有与任何其他关系指定关系,那么只有它在PrimaryName和SecondaryName中显示应为空或null。

我试图获得预期的结果。

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

1 个答案:

答案 0 :(得分: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