2015-05-14 119 views
1

我有如下2010 MS-訪問SQL查詢:申請和

SELECT 
    EXC AS MY_EXC, 
    COUNT(FC_CUSIP) AS MY_FC_CUSIP 
FROM 
    TESTDATA t 
WHERE 
    FC_CUSIP <> "NULL" 
GROUP BY 
    EXC 
UNION ALL 
SELECT 
    EXC AS MY_EXC, 
    0 AS MY_FC_CUSIP 
FROM 
    TESTDATA t 
WHERE 
    FC_CUSIP = "NULL" 
GROUP BY 
    EXC 
ORDER BY 
    MY_EXC ASC; 

結果如下:

MY_EXC | MY_FC_CUSIP 
--------+--------------- 
AA  | 0 
AM  | 0 
AM  | 9 
BB  | 0 
DD  | 10 
DD  | 0 
F  | 0 
I  | 0 
NM  | 0 
NM  | 131 
NY  | 0 
NY  | 184 
OO  | 0 
OO  | 14 
PC  | 0 
VA  | 0 
Z  | 0 
Z  | 2 

我需要進一步的SQL這可以給出結果等作爲下面: 基本上它將不同MY_EXC和總和即MY_FC_CUSIP

MY_EXC | MY_FC_CUSIP 
--------+--------------- 
AA  | 0 
AM  | 9  
BB  | 0  
DD  | 10 
F  | 0 
I  | 0 
NM  | 131 
NY  | 184 
OO  | 14 
PC  | 0 
VA  | 0 
Z  | 2 

PLE ase以任何方式幫助我......實際上,我通過VBA動態創建了整個sql字符串。

回答

1
SELECT a.MY_EXC, SUM(a.MY_FC_CUSIP) 
FROM (SELECT EXC AS MY_EXC, COUNT(FC_CUSIP) AS MY_FC_CUSIP 
     FROM TESTDATA t 
     WHERE FC_CUSIP <> "NULL" 
     GROUP BY EXC 
     UNION ALL 
     SELECT EXC AS MY_EXC, 0 AS MY_FC_CUSIP 
     FROM TESTDATA t 
     WHERE FC_CUSIP = "NULL" 
     GROUP BY EXC) 
GROUP BY a.MY_EXC 
+0

我已經嘗試過這樣的: – pmr

+0

它給出了查詢操作的語法錯誤(缺少操作)「a.MY_EXC SUM(a.MY_FC_CUSIP)」 – pmr

+0

@purnendumaity現在嘗試,錯過了一個逗號 – Matt

1

MS Access在子查詢中不支持union。然而,在你的情況,你可以簡化查詢:

SELECT EXC AS MY_EXC, 
     SUM(IIF(FC_CUSIP <> "NULL", 1, 0)) AS MY_FC_CUSIP 
FROM TESTDATA 
GROUP BY EXC 
ORDER BY MY_EXC ASC; 
+0

...它給出了正確的結果,但要求對話框的警告,如輸入參數爲「MY_EXC」與確定/取消對話框,如果我只是點擊2時間確定/取消然後只有它給出結果.......我通過VBA在後端運行整個事情...所以如何進展或任何其他方式? – pmr

+0

@戈登...明白了......我必須刪除這個ORDER BY MY_EXC ASC;無論如何沒有這些數據在EXC欄中都是按照正確的順序進行的 – pmr