SQL分区检查

时间:2016-10-26 00:41:01

标签: sql-server tsql

在Microsoft SQL中,假设有两列c1c2。如何检查c2分区是c1的函数?

通过c2分区或c1的函数,我的意思是具有不同c2属性的行不能具有相同的c1属性。同样,我想提取具有相同c1属性但不同c2属性的行。

我当然可以构造行集,其中每个集合都是具有任意给定c2属性的行集合。然后我们检查所有n(n-1)/ 2个交叉点是否都是空的。

除了最后一段描述的那种繁琐的代码之外,还有一小段代码可以实现这一目标吗?

下面我展示两个例子。左表c2c1的函数,而c2不是右表中c1的函数。

Example

2 个答案:

答案 0 :(得分:2)

我猜测这里没有提到的问题是SQL SERVER在分析函数中不支持 DISTINCT

错误: OVER子句不允许使用DISTINCT。

select      c1
           ,c2

from       (select      c1
                       ,c2
                       ,min (c2) over (partition by c1) as min_c2
                       ,max (c2) over (partition by c1) as max_c2

            from        t
            ) t

where       min_c2 <> max_c2
;
c1  c2
2   1
2   2
4   2
4   3

其他解决方案,只是为了它的乐趣:

select      c1
           ,c2

from       (select      c1
                       ,c2
                       ,count (*) over (partition by c1)    as c2_val

            from       (select      distinct

                                    c1
                                   ,c2

                        from        t2
                        ) t
            ) t

where       c2_val > 1
;

答案 1 :(得分:1)

如果我们事先知道行是完全不同的,我们有

select c1, c2
from 
    (select c1, c2, count(distinct(c2)) over (partition by c1) as count
    from table) table1
where count>1

如果我们不知道所有行的清晰度,那么代码就是

select c1, c2
from 
    (select c1, c2, count(c2) over (partition by c1) as count
    from 
        (select distinct c1,c2
         from table0
        ) table 
     ) table
where count>1