进行正确的连接并使用STUFF

时间:2018-10-24 14:25:17

标签: sql-server

我有2张桌子。

塔贝尔T1:

-----ID-----Name----
     1       P1
     2       P2
     3       P3

塔贝尔T2:

-----ID-----PID----Type
     1       1      T1 
     1       2      T2
     1       3      T1
     2       4      T3
     2       5      T3

我想要什么:

  ----Name----Different_Types-----Type_Names
       P1           2               T1,T2 

我尝试过的:

Select distinct T1.NAME,
                count(distinct T2.Type) as Different_Types,
                from T1
                left join T2
                on T2.ID = T1.ID
                having count(distinct T2.PID) > 2
                order by Different_Types desc

在此查询中,我在所需的表中有前两列,但是在添加第三列时遇到了麻烦。...有什么主意吗?

1 个答案:

答案 0 :(得分:3)

认为这应该做您想要做的事

DECLARE @T1 TABLE
(
    ID INT NOT NULL,
    Name CHAR(2) NOT NULL
);

INSERT INTO @T1
VALUES (1,'P1'),(2,'P2'),(3,'P3');

DECLARE @T2 TABLE
(
    ID INT NOT NULL,
    PID INT NOT NULL,
    TypeName CHAR(2) NOT NULL
);

INSERT INTO @T2
VALUES (1,1,'T1'),(1,2,'T2'),(1,3,'T1'),(2,4,'T3'),(2,5,'T3');

SELECT  T1.Name,
        COUNT(DISTINCT T2.TypeName) AS Different_Types,
        STUFF((
                    SELECT  ',' + T.TypeName
                    FROM    @T2 AS T
                    WHERE   T1.ID = T.ID
                    GROUP   BY T.TypeName
                    FOR XML PATH(''), TYPE).value('.', 'varchar(max)')
                ,1,1,'')
FROM    @T1 AS T1
INNER
JOIN    @T2 AS T2
        ON  T1.ID = T2.ID
GROUP   BY T1.ID, T1.Name
HAVING  COUNT(DISTINCT T2.PID) > 2;

编辑:

在引用Haveing子句中的T2表时,将LEFT更改为INNER联接。