MySQL与UNION加倍

时间:2015-07-31 15:49:24

标签: mysql union

以下请求包含2个子查询。这些子查询中的每一个都可以正常工作。他们的UNION产生双倍。如果子查询1给出5行,子查询2 10行,则UNION产生30行。我的问题:我如何删除这些副本

SELECT annee, cle, situation
FROM
(
    SELECT  sq1.annee AS annee, 
            sq1.cle AS cle, 
            sq1.montantC - sq1.montantD AS situation
    FROM    
        (
            SELECT YEAR(e.oe_date_ope) as annee, CONCAT(YEAR(e.oe_date_ope)," | ", e.oe_im_id," | ", c.cp_pa_id) as cle,
                SUM(IF(m.om_dc = "C" , m.om_mtt ,0)) as montantC , SUM(IF(m.om_dc = "D" , m.om_mtt ,0)) as montantD 
            FROM ope_entetes e
            LEFT JOIN ope_mtts m ON e.oe_id = m.om_oe_id
            LEFT JOIN comptes c ON m.om_cp_id = c.cp_id
            GROUP BY cle
            HAVING annee <= '2014'
        ) AS sq1
    GROUP BY sq1.cle    

    UNION

    SELECT sq2.annee AS annee, sq2.cle AS cle, sq2.montantC - sq2.montantD AS situation
    FROM
        (
            SELECT YEAR(e.oe_date_ope) as annee, CONCAT(YEAR(e.oe_date_ope)," | ", e.oe_im_id," | ", c.cp_pa_id," | ",n.na_id) as cle,
                SUM(IF(m.om_dc = "C" , m.om_mtt ,0)) as montantC , SUM(IF(m.om_dc = "D" , m.om_mtt ,0)) as montantD 
            FROM ope_entetes e
            LEFT JOIN ope_mtts m ON e.oe_id = m.om_oe_id
            LEFT JOIN comptes c ON m.om_cp_id = c.cp_id
            LEFT JOIN natures n ON e.oe_na_id = n.na_id
            WHERE n.na_id = 4
            GROUP BY cle
            HAVING annee <= '2014'
        ) AS sq2
    GROUP BY sq2.cle
) AS sq
GROUP BY cle
ORDER BY cle

0 个答案:

没有答案