一个简单的查询就是重复记录

时间:2013-10-25 05:36:09

标签: sql-server duplicates record

我有两(2)张表。第一个名为TABLE的N行具有唯一的_A(KEY),第二个名为TABLE_AUX的行为0,那么我只是运行下一个查询:

INSERT INTO TABLE_AUX(_A,_B,_C) 
SELECT A,B,C FROM TABLE;

在评估查询后,我有:

a) N = SELECT COUNT(1) FROM TABLE = SELECT COUNT(1) FROM TABLE_AUX

b) K = SELECT SUM(Q.CNT-1) 
       FROM ( SELECT COUNT(1) as CNT, _A 
              FROM TABLE_AUX GROUP BY _A HAVING COUNT(1)>1
       ) Q;

c) M = SELECT COUNT(Q._A) 
       FROM (SELECT DISTINCT _A 
             FROM TABLE_AUX) Q

, WHERE N = M + K, then M < N 

d) Zero = 0 = SELECT COUNT(1) 
              FROM TABLE T 
              WHERE NOT EXISTS ( SELECT * 
                                 FROM TABLE_AUX TA 
                                 WHERE TA._A = T._A );

e) P = SELECT COUNT(1) FROM TABLE T, TABLE_AUX TA WHERE T._A = TA._A;

, WHERE P = N + K, then N < P

很奇怪,在某些情况下会有重复的结果。但并非在所有情况下。有人知道会发生什么吗?

1 个答案:

答案 0 :(得分:0)

在选择查询中使用Distinct关键字。

INSERT INTO TABLE_AUX(_A,_B,_C) 
SELECT DISTINCT A,B,C FROM TABLE;