Union Subquery生成结果非联合子查询没有

时间:2014-08-06 20:32:37

标签: sql ms-access ms-access-2010

我正在使用Access 2010,我的查询结果非常奇怪。

我创建了一个包含生成结果的union子查询的查询。我还创建了一个具有非联合子查询的查询,该子查询不会产生任何记录。这很奇怪,因为union子查询是两次非联合子查询。

非联盟子查询:

SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
    FROM AGGDATA 
    GROUP BY [NVP NAME],NVP,[BASE PERIOD]

Unioned Subquery:

SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
    FROM AGGDATA
    GROUP BY [NVP NAME],NVP,[BASE PERIOD]
    UNION
    SELECT NVP, [NVP NAME], MIN([CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
    FROM AGGDATA 
    GROUP BY [NVP NAME],NVP,[BASE PERIOD]

以下是整个查询:

SELECT sub.NVP,sub.[NVP NAME], SUB.[MIN PERIOD], SUB.[BASE PERIOD], TT.[ACTIVE PERIODS]
FROM 
    (SELECT AGGD.NVP, AGGD.[NVP NAME], MIN(AGGD.[CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
    FROM AGGDATA AGGD 
    GROUP BY AGGD.[NVP NAME],AGGD.NVP,[BASE PERIOD]
    UNION
    SELECT AGGD.NVP, AGGD.[NVP NAME], MIN(AGGD.[CURRENT PERIOD]) AS [MIN PERIOD], [BASE PERIOD]
    FROM AGGDATA AGGD 
    GROUP BY AGGD.[NVP NAME],AGGD.NVP,[BASE PERIOD])  
    AS SUB 
INNER JOIN 

    (SELECT SUB.NVP, 
        SUB.[BASE PERIOD], 
        COUNT([CURRENT PERIOD]) AS [ACTIVE PERIODS]

    FROM
        (SELECT DISTINCT NVP, [BASE PERIOD], [CURRENT PERIOD]
                FROM AGGDATA) 
        AS SUB

    GROUP BY SUB.NVP, SUB.[BASE PERIOD] 
having COUNT([CURRENT PERIOD]) < 10)  
AS TT 
ON SUB.[BASE PERIOD] = TT.[BASE PERIOD] AND SUB.NVP = TT.NVP
WHERE SUB.[MIN PERIOD] > TT.[BASE PERIOD]

有谁知道为什么Union子查询可以工作但是非联合子查询没有?

编辑:两个子查询确实产生相同的结果,问题在于整个查询。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您的括号和别名存在一些问题。请尝试使用此代码:

SELECT 
    mn.NVP,[NVP NAME], [MIN PERIOD], mn.[BASE PERIOD], TT.[ACTIVE PERIODS]
FROM 
    (SELECT 
        [NVP NAME],NVP,[BASE PERIOD], MIN([CURRENT PERIOD]) AS [MIN PERIOD]
    FROM 
        AGGDATA  
    GROUP BY 
        [NVP NAME],NVP,[BASE PERIOD])      AS mn INNER JOIN 
    (SELECT 
        NVP, 
        [BASE PERIOD], 
        COUNT([CURRENT PERIOD]) AS [ACTIVE PERIODS]
    FROM
        (SELECT DISTINCT 
            NVP, [BASE PERIOD], [CURRENT PERIOD]
          FROM 
            AGGDATA)         AS a
    GROUP BY 
        NVP, [BASE PERIOD] 
    HAVING 
        COUNT([CURRENT PERIOD]) < 10)  AS TT ON 
    mn.[BASE PERIOD] = TT.[BASE PERIOD] AND 
    mn.NVP = TT.NVP
WHERE 
    mn.[MIN PERIOD] > TT.[BASE PERIOD]