简体   繁体   中英

add a row to query in MS-ACCESS SQL

I'm trying to add to the following query:

    strSQL = "SELECT  fldName, blkName, CDbl(fldValue) " & _
        "FROM dbSecurities2 as S " & _
        "WHERE " & _
        "S.isin='" & Code & "' " & _
        "AND " & _
        "S.fldName='" & fldName & "' "

A row that makes the sum of the fldValue like:

    strSQL = "SELECT  fldName, blkName, CDbl(fldValue) " & _
        "FROM dbSecurities2 as S " & _
        "UNION " & _
        "SELECT Sum(fldValue) AS fldValue " & _
        "WHERE " & _
        "S.isin='" & Code & "' " & _
        "AND " & _
        "S.fldName='" & fldName & "' "

the error is:

Run -time error '3141'. The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect

I found this is working:

   strSQL = "SELECT fldName, blkName, CDbl(fldValue) " & _
        "FROM dbSecurities2 as S " & _
        "WHERE " & _
        "S.isin='" & Code & "' " & _
        "AND " & _
        "S.fldName='" & fldName & "' " & _
        "UNION " & _
        "SELECT '' AS fldName, 'Total' AS Total, Sum(CDbl(fldValue)) " & _
        "FROM dbSecurities2 AS B " & _
        "WHERE " & _
        "B.isin='" & Code & "' " & _
        "AND " & _
        "B.fldName='" & fldName & "' "

This should run as expected:

    strSQL = "SELECT fldName, blkName, CDbl(fldValue) " & _
        "FROM dbSecurities2 AS S " & _
        "WHERE " & _
        "S.isin='" & Code & "' " & _
        "AND " & _
        "S.fldName='" & fldName & "' " & _
        "UNION ALL " & _
        "SELECT TOP 1 "", "Total", Sum(CDbl(fldValue)) " & _
        "FROM dbSecurities2"

If you have Null values, use Nz :

    strSQL = "SELECT fldName, blkName, CDbl(Nz(fldValue, 0)) " & _
        "FROM dbSecurities2 AS S " & _
        "WHERE " & _
        "S.isin='" & Code & "' " & _
        "AND " & _
        "S.fldName='" & fldName & "' " & _
        "UNION ALL " & _
        "SELECT TOP 1 "", "Total", Sum(CDbl(Nz(fldValue, 0))) " & _
        "FROM dbSecurities2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM