SQL GROUP BY HAVING问题

时间:2012-03-27 19:55:00

标签: group-by sql-server-2000 having

我有两个记录表,我需要找到所有匹配项。这些表基于不同的主键标识符,但数据点完全相同。我需要一个快速查询,可以显示从第一个表到第二个表重复的记录。这是我想要做的一个例子:

DECLARE @Table1 TABLE (ID INT, Value INT)
DECLARE @Table2 TABLE (ID INT, Value INT)

INSERT INTO @Table1 VALUES (1, 500)
INSERT INTO @Table1 VALUES (2, 500)

INSERT INTO @Table2 VALUES (3, 500)
INSERT INTO @Table2 VALUES (4, 500)

SELECT  MAX(x.T1ID)
        ,MAX(x.T2ID)
FROM    (
            SELECT  T1ID = t1.ID
                    ,T2ID = 0
                    ,t1.Value
            FROM    @Table1 t1
            UNION ALL
            SELECT  T1ID = 0
                    ,T2ID = t2.ID
                    ,t2.Value
            FROM    @Table2 t2
        ) x
GROUP BY x.Value
HAVING COUNT(*) >= 2

此代码的问题在于它返回表1中与表2中记录4相关的记录2.我真的需要它返回表1中与表2中记录3相关的记录1.我尝试了以下内容:< / p>

SELECT  MIN(x.T1ID)
        ,MIN(x.T2ID)
FROM    (
            SELECT  T1ID = t1.ID
                    ,T2ID = 0
                    ,t1.Value
            FROM    @Table1 t1
            UNION ALL
            SELECT  T1ID = 0
                    ,T2ID = t2.ID
                    ,t2.Value
            FROM    @Table2 t2
        ) x
GROUP BY x.Value
HAVING COUNT(*) >= 2

此代码也不起作用。它返回0,0。

是否有办法为两个表返回大于0的MIN值?

2 个答案:

答案 0 :(得分:0)

可能会回答我自己的问题。这似乎有效。我有什么理由不这样做吗?

SELECT  MIN(t1.ID)
        ,MIN(t2.ID)
FROM    @Table1 t1
        INNER JOIN @Table2 t2 ON t1.Value = t2.Value
GROUP BY t1.Value

答案 1 :(得分:0)

如果要查看table1中在table2中有匹配的记录,那么

select *
from @Table1 T1
where exists (select * from @Table2 T2
where T1.ID=T2.ID 
-- you would put the complete join clause that defines a match here
)