2

I'm having issues with my SQL Server code. I am trying to get results to list by the first 4 columns of the select statement. I keep getting syntax errors and am unsure as to why.

What I want it to do is pull by the entityid, acctnum, period that I define but, I don't want to see the period in the results as I want them to be summed together. IE I want see the total activity for the activity column instead of rows for each period.

SELECT 
    ENTITYID, ACCTNUM, ACCTNAME, ACTIVITY
FROM
    (SELECT  
         g.ENTITYID AS 'ENTITYID'
         g.ACCTNUM AS 'ACCTNUM'
         SUM(g.ACTIVITY) AS 'ACTIVITY'
         h.ACCTNAME AS 'ACCTNAME'
     FROM 
         SQLDATA.DBO.GLSUM  g
     INNER JOIN 
         SQLDATA.DBO.GACC h ON g.ACCTNUM = h.ACCTNUM
     WHERE   
         g.ENTITYID = '85000'
         g.PERIOD < '201703'
         g.ACCTNUM = '569300000')
5
  • 2
    Are you going to share the error message with us? You are missing a closing ) somewhere. Commented Apr 7, 2017 at 17:39
  • There is an error in the SQL Statement, Incorrect syntax near 'g' Commented Apr 7, 2017 at 17:39
  • Looks like you are missing a closed parenthesis. Commented Apr 7, 2017 at 17:40
  • you query is not even complete Commented Apr 7, 2017 at 17:40
  • Shouldn't you close the "(" you opened after FROM? Commented Apr 7, 2017 at 17:40

2 Answers 2

2

You need a GROUP BY clause https://learn.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql, commas in the SELECT list, AND keywords between WHERE elements, and the outer select seems a bit redundant.

SELECT  
    g.ENTITYID AS 'ENTITYID',
    g.ACCTNUM AS 'ACCTNUM',
    SUM(g.ACTIVITY) AS 'ACTIVITY',
    h.ACCTNAME AS 'ACCTNAME'
FROM 
    SQLDATA.DBO.GLSUM  g
INNER JOIN 
    SQLDATA.DBO.GACC h ON g.ACCTNUM = h.ACCTNUM
WHERE   
    g.ENTITYID = '85000'
    AND g.PERIOD < '201703'
    AND g.ACCTNUM = '569300000' 
GROUP BY  
    g.ENTITYID,
    g.ACCTNUM,
    h.ACCTNAME
Sign up to request clarification or add additional context in comments.

1 Comment

I still get the same "There is an error in the SQL statement, Incorrect syntax near 'g'."
0
DECLARE @a int 
SET @a = select sum(g.ACTIVITY) 
         from SQLDATA.DBO.GLSUM  
         WHERE ENTITYID = '85000' and
               PERIOD < '201703' and
               ACCTNUM = '569300000' 



SELECT  

           g.ENTITYID AS 'ENTITYID'
           g.ACCTNUM AS 'ACCTNUM'
           @a AS 'ACTIVITY'
           h.ACCTNAME AS 'ACCTNAME'

FROM SQLDATA.DBO.GLSUM  g
INNER JOIN SQLDATA.DBO.GACC h
ON g.ACCTNUM = h.ACCTNUM

WHERE   

           g.ENTITYID = '85000'
           g.PERIOD < '201703'
           g.ACCTNUM = '569300000' 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.