2017-02-06 54 views
0

問題如下。我有以下SQL語句:如何定義嵌套的SQL語句來返回計算值?

// SQL statement for ms access 2010 
SELECT 
    ID, SUM(fund_assets) AS Sum_FV, COUNT(*) AS DataCount, 
    (Sum_FV/DataCount) AS Result 
FROM 
    V_Assets_L12 
WHERE 
    Datum >= DATEADD("m", -12, #6/2/2017#) 
    AND Datum <= #6/2/2017# 
    AND ID = 325 
GROUP BY 
    ID 
ORDER BY 
    ID; 

結果是正確的ONE ID!但我需要V_Assets_L12的所有現有ID的列表。所以我的第一個想法是定義一個嵌套的SQL語句如下:

SELECT 
    ID, SUM(fund_assets) AS Sum_FV, COUNT(*) AS DataCount, 
    (Sum_FV/DataCount) AS Result 
FROM 
    V_Assets_L12 
WHERE 
    Datum >= DATEADD("m", -12, #6/2/2017#) 
    AND Datum <= #6/2/2017# 
    AND ID IN (SELECT DISTINCT ID 
       FROM V_Assets_L12 
       ORDER BY ID ASC) 
GROUP BY 
    ID 
ORDER BY 
    ID; 

但這不適用於我。我錯了什麼?

回答

1

你可以只取出WHERE子句中的條件:

SELECT ID, SUM(fund_assets) AS Sum_FV, COUNT(*) AS DataCount, 
     (Sum_FV/DataCount) AS Result 
FROM V_Assets_L12 
WHERE Datum >= DateAdd("m", -12, #6/2/2017#) And 
     Datum <= #6/2/2017# 
GROUP BY ID 
ORDER BY ID; 
+0

感謝您的答案......這是解決:) – yuro

+0

如果我要選擇3個標識例如什麼是325,466和30014.我該如何解決這個問題? – yuro

+1

好吧,我用'IN'示例解決了它:) – yuro