用于确定列中值是否唯一的案例陈述

时间:2015-07-24 11:21:30

标签: sql-server tsql

我想知道一个' Activity_ID'对于每个提供商来说都是独一无二的,理想情况下,我希望通过案例陈述来做到这一点。

如果我写一个案例陈述来向您展示我想如何处理这个问题,那么它可能更有意义;

 CASE WHEN Concat (Activity_ID,Provider) IS **UNIQUE/DISTINCT** THEN 'Yes'
   ELSE 'No'
   END 'Unique_Flag'

   --Concat has been used as it is possible for a Provider to have an Activity_ID
     which is also used by another provider, however there is no connection and i am 
     only interested in if an Activity_ID is unique for an indvidual provider

我希望结果如下所示。我相信我很接近,只需要用适当的命令替换上面的 UNIQUE / DISTINCT

Provider       Activity_ID    Unique_Flag
ProvA              11           Yes
ProvA              22           No
ProvA              22           No
ProvA              33           Yes
ProvA              44           Yes  
ProvA              55           Yes
ProvB              55           No
ProvB              55           No

2 个答案:

答案 0 :(得分:4)

SELECT CASE WHEN COUNT(*) OVER (PARTITION BY Provider, Activity_ID) > 1 THEN 'No' ELSE 'Unique' END, *
FROM ...

使用像这样的OVER子句将在不同的数据窗口中运行聚合,从而允许您按这两列进行分组而不会破坏集合的其余部分。

答案 1 :(得分:0)

有几种方法可以实现这一目标。您可以使用派生表,例如:

    --Sample Table and Data
    DECLARE @table TABLE
    (
        Provider VARCHAR(5),
        Activity_ID TINYINT
    )

    INSERT INTO @table 
    VALUES
    ('ProvA',11),
    ('ProvA',22),
    ('ProvA',22),
    ('ProvA',33),
    ('ProvA',44),
    ('ProvA',55),
    ('ProvB',55),
    ('ProvB',55)

    -- Your desired query using a derived table
    SELECT  t.Provider, t.Activity_ID,
            CASE WHEN t2.Cnt = 1 
                THEN 'Yes'
                ELSE 'No'
            END AS Unique_Flag
    FROM    @table t
            INNER JOIN
            (SELECT Provider, Activity_ID, COUNT(*) AS Cnt
            FROM    @table
            GROUP BY Provider,Activity_ID) t2 
                ON t.Provider = t2.Provider
                AND t.Activity_ID = t2.Activity_ID