加入2个查询...错误同时拉出某些字段

时间:2014-10-15 18:18:12

标签: sql sql-server sql-server-2008

我正在尝试加入2个查询&从连接中获取某些列。但是我收到了一个错误。你能帮我理解我错在哪里 -

SELECT X.*,Y.* FROM
(
    (
    SELECT  
        C1,C2,C3
        COUNT(C4) AS CNT    -- count
    FROM [dbo].[Tb1]
    WHERE C1 <> 0 AND    -- amount not = zero
        C2 = 'F'        -- flag
    GROUP BY C1,C2,C3
    HAVING COUNT(C4) > 1
    )X
    INNER JOIN
    (SELECT * FROM [dbo].[Tb1])Y
    ON
        X.C1 = Y.C1            
    AND X.C2 = Y.C2            
    AND X.C3=Y.C3             
    AND X.C4=Y.C4             
)

第一个查询可以帮助我获得重复的信息。第二个查询将帮助我从同一个表中获取其他字段。

感谢。

1 个答案:

答案 0 :(得分:1)

解决方案#1:

SELECT X.*,Y.* FROM
--( <-- (1) comment  this line
    (
    SELECT  
        C1,C2,C3, -- <-- (2) add , after C3
        COUNT(C4) AS CNT    -- count
    FROM [dbo].[Tb1]
    WHERE C1 <> 0 AND   -- amount not = zero
        C2 = 'F'        -- flag
    GROUP BY C1,C2,C3
    HAVING COUNT(C4) > 1
    )X
    INNER JOIN
    (SELECT * FROM [dbo].[Tb1])Y
    ON
        X.C1 = Y.C1            
    AND X.C2 = Y.C2            
    AND X.C3=Y.C3             
    AND X.CNT=Y.C4 <-- see   anir's comment            
--) <-- (3) comment  this line

解决方案#2:

SELECT  X.*, Y.* 
FROM
(
    SELECT  
        C1,C2,C3, 
        COUNT(C4) AS CNT    -- count
    FROM [dbo].[Tb1]
    WHERE 
        C1 <> 0 AND    -- amount not = zero
        C2 = 'F'       -- flag
    GROUP BY C1,C2,C3
    HAVING COUNT(C4) > 1
) X
INNER JOIN [dbo].[Tb1] Y
ON  X.C1 = Y.C1            
    AND X.C2 = Y.C2            
    AND X.C3=Y.C3             
    AND X.CNT=Y.C4 <-- see   anir's comment            

注意#1:当CNT&gt; 1和x.C1,y.C1包含NULL然后X.C1 = Y.C1&lt; =&gt; NULL = NULL如果ANSI_NULLS为ON,则计算为UNKNOWN。这意味着将从最终结果集中删除这些行。这同样适用于X.C2 = Y.C2和X.C3 = Y.C3。

SET ANSI_NULLS ON
SELECT CASE WHEN NULL = NULL THEN 1 ELSE 0 END AS T1
SET ANSI_NULLS OFF
SELECT CASE WHEN NULL = NULL THEN 1 ELSE 0 END AS T2
/*
T1
-----------
0

T2
-----------
1
*/

注意#2:"In a future version of SQL Server, ANSI_NULLS will always be ON and any applications that explicitly set the option to OFF will generate an error."

解决方案#3:

SELECT  y.*
FROM 
(
    SELECT  x.*, COUNT(x.C4) OVER(PARTITION BY x.C1, x.C2, x.C3) AS CNT    -- count
    FROM    [dbo].[Tb1] x
    WHERE 
        x.C1 <> 0 AND   -- amount not = zero
        x.C2 = 'F'      -- flag
        -- AND x.C1 IS NOT NULL AND x.C2 IS NOT NULL AND x.C3 IS NOT NULL ?
) y
WHERE y.CNT > 1 AND y.CNT = y.C4