2012-10-16 125 views
0

我得到了下面的查詢:SQL UNION語句

SELECT 
     ep_101.cd_hfdmapnr AS Dossiernummer, 
     SUM(ep_102.id_fhmbdlv) AS Kosten 

    FROM ep_101 

    INNER JOIN et_101 ON ep_101.cd_hfdmapnr = et_101.cd_hfdmapnr 
    INNER JOIN ep_102 ON ep_101.cd_hfdmapnr = ep_102.cd_hfdmapnr 

    WHERE ep_101.cd_mapkverw = 0 
    AND ep_102.cd_bkcode = '000010' 
    AND et_101.opdrachtgever1 = '05354605' 

    GROUP BY ep_101.cd_hfdmapnr 

    UNION 

    SELECT 
     ep_101.cd_hfdmapnr AS Dossiernummer, 
     SUM(ep_102.id_fhmbdlv) AS GriffieKosten 

    FROM ep_101 

    INNER JOIN et_101 ON ep_101.cd_hfdmapnr = et_101.cd_hfdmapnr 
    INNER JOIN ep_102 ON ep_101.cd_hfdmapnr = ep_102.cd_hfdmapnr 

    WHERE ep_101.cd_mapkverw = 0 
    AND ep_102.cd_bkcode = '000020' 
    AND et_101.opdrachtgever1 = '05354605' 

    GROUP BY ep_101.cd_hfdmapnr 

雖然結果只給回Dossiernummer & Kosten我怎樣才能重新它使「Griffiekosten」也顯示?因爲我的想法....

回答

1

如果你真的需要顯示它在兩列:

SELECT 
    ep_101.cd_hfdmapnr AS Dossiernummer, 
    SUM(case when ep_102.cd_bkcode = '000010' then ep_102.id_fhmbdlv else 0 end) AS Kosten, 
    SUM(case when ep_102.cd_bkcode = '000020' then ep_102.id_fhmbdlv else 0 end) AS GriffieKosten 
FROM ep_101 
    INNER JOIN et_101 ON ep_101.cd_hfdmapnr = et_101.cd_hfdmapnr 
    INNER JOIN ep_102 ON ep_101.cd_hfdmapnr = ep_102.cd_hfdmapnr 
WHERE ep_101.cd_mapkverw = 0 
    AND ep_102.cd_bkcode in ('000010', '000020') 
    AND et_101.opdrachtgever1 = '05354605' 
GROUP BY ep_101.cd_hfdmapnr 
+0

修復那麼你的'組by'條款。 –

+0

工作感謝ALLOT! –

0

它們顯示!
當您使用UNION時,列名將根據UNION中的名字排序,在此情況下爲:Dossiernummer & Kosten。

只是一個小問題,你確定要使用UNION嗎? Kosten和Griffiekosten是一樣的嗎?如果不是那麼UNION是錯誤的路要走。

假設他們是不同類型的值,但您希望結果顯示每個Dossiernummer,那麼您正在查看JOIN(在Dossiernummer上)。

線沿線的東西:

SELECT Isnull(T1.DOSSIERNUMMER, T2.DOSSIERNUMMER) AS Dossiernummer, 
     T1.KOSTEN, 
     T2.GRIFFIEKOSTEN 
FROM (SELECT EP_101.CD_HFDMAPNR  AS Dossiernummer, 
       Sum(EP_102.ID_FHMBDLV) AS Kosten 
     FROM EP_101 
       INNER JOIN ET_101 
         ON EP_101.CD_HFDMAPNR = ET_101.CD_HFDMAPNR 
       INNER JOIN EP_102 
         ON EP_101.CD_HFDMAPNR = EP_102.CD_HFDMAPNR 
     WHERE EP_101.CD_MAPKVERW = 0 
       AND EP_102.CD_BKCODE = '000010' 
       AND ET_101.OPDRACHTGEVER1 = '05354605' 
     GROUP BY EP_101.CD_HFDMAPNR)T1 
     FULL OUTER JOIN (SELECT EP_101.CD_HFDMAPNR  AS Dossiernummer, 
           Sum(EP_102.ID_FHMBDLV) AS GriffieKosten 
         FROM EP_101 
           INNER JOIN ET_101 
             ON EP_101.CD_HFDMAPNR = 
              ET_101.CD_HFDMAPNR 
           INNER JOIN EP_102 
             ON EP_101.CD_HFDMAPNR = 
              EP_102.CD_HFDMAPNR 
         WHERE EP_101.CD_MAPKVERW = 0 
           AND EP_102.CD_BKCODE = '000020' 
           AND ET_101.OPDRACHTGEVER1 = '05354605' 
         GROUP BY EP_101.CD_HFDMAPNR)T2 
        ON T1.DOSSIERNUMMER = T2.DOSSIERNUMMER 
+0

走什麼路? 2首先在bkcode 000010上進行sql查詢過濾,另一個在000020上進行過濾,這樣就會有不同的結果,會給出2個完全不同的結果,那麼結果如何呢? –