使用CTE比较多行数据

时间:2016-03-08 22:13:32

标签: tsql recursion sql-server-2012 rows common-table-expression

在此数据集中,我需要标记出应用程序ID P-10900,因为它被2个TeamMember触及。 我们可以将标记形式标记为单独的列。

我知道可以使用递归CTE轻松完成,但不知道如何编写语法。

TeamMember      Status      ApplicationID
NULL            NW          P-10900
John            IR          P-10900
John            CO          P-10900
Dick            IR          P-10900
Dick            PA          P-10900
NULL            NW          P-06700
John            IR          P-06700
John            PA          P-06700
NULL            NW          P-14600
Andre           IR          P-14600

这是对此处提出的问题的扩展

Find which rows have different values for a given column in SQL

我正在使用MS SQL Server 2012

我期待这样的输出:

TeamMember        Status        ApplicationID   Flag
NULL              NW            P-10900         Dup
John              IR            P-10900         Dup
John              CO            P-10900         Dup
Dick              IR            P-10900         Dup
Dick              PA            P-10900         Dup
NULL              NW            P-06700         Alike   
John              IR            P-06700         Alike
John              PA            P-06700         Alike
NULL              NW            P-14600         Alike
Andre             IR            P-14600         Alike

以下是架构:

CREATE TABLE App
    ([TeamMember] varchar(5), [aStatus] varchar(2), [ApplicationID] varchar(7))
;

INSERT INTO App
    ([TeamMember], [aStatus], [ApplicationID])
VALUES
    (NULL, 'NW', 'P-10900'),
    ('John', 'IR', 'P-10900'),
    ('John', 'CO', 'P-10900'),
    ('Dick', 'IR', 'P-10900'),
    ('Dick', 'PA', 'P-10900'),
    (NULL, 'NW', 'P-06700'),
    ('John', 'IR', 'P-06700'),
    ('John', 'PA', 'P-06700'),
    (NULL, 'NW', 'P-14600'),
    ('Andre', 'IR', 'P-14600')
;

这就是我尝试过哪种方法不起作用:

 WITH cte (applicationid, status, teammember)
     AS (SELECT applicationid,
                status,
                teammember
         FROM   app
         GROUP  BY applicationid,
                   status,
                   teammember)
SELECT applicationid,
       teammember,
       status,
       CASE
         WHEN (SELECT DISTINCT CASE
                                 WHEN Count(applicationid) > 1 THEN 'Alike'
                                 ELSE 'Dup'
                               END
               FROM   cte B
               WHERE  B.teammember = A.teammember
               GROUP  BY B.teammember) = 'Alike' THEN 'Alike'
         ELSE 'Dup'
       END AS Flag
FROM   cte A
ORDER  BY applicationid  

1 个答案:

答案 0 :(得分:1)

你只是过分复杂的事情。你根本不需要CTE:

SPContextFilter