0
votes

I have a query that returns records but does not GROUP. I have tried several SELECT BY and GROUP option, none work??

This returns multiple records for each s.surname??

sql_staff = """SELECT s.surname, s.forename, s.status, s.staff_id, 
    s.Staff_status, 
    g.id,          
    g.cluster_id as g_cluster_id, 
    gc.cluster_id as gc_cluster_id        
    FROM staff s INNER JOIN local_grant_investigators lgi
    ON s.staff_id = lgi.staff_id

    INNER JOIN grants g
    ON g.id = lgi.grant_id        

    INNER JOIN grant_clusters gc
    ON g.id=gc.grant_id
    WHERE s.Staff_status=1
    GROUP BY s.surname, s.forename, s.status, s.staff_id, s.Staff_status,
    g.id, g.cluster_id, 
    gc.cluster_id HAVING s.Staff_status=1
    ORDER BY s.surname, s.forename;    
"""
r_s = list(conn.execute(text(sql_staff)))

This code below throws an error??

sql_staff = """SELECT s.surname, s.forename, s.status, s.staff_id, 
    s.Staff_status,
    g.id,          
    g.cluster_id as g_cluster_id, 
    gc.cluster_id as gc_cluster_id        
    FROM staff s INNER JOIN local_grant_investigators lgi
    ON s.staff_id = lgi.staff_id 
    GROUP BY s.surname, s.forename, lgi.staff_id        

    INNER JOIN grants g
    ON g.id = lgi.grant_id        

    INNER JOIN grant_clusters gc
    ON g.id=gc.grant_id
    WHERE s.Staff_status=1
    GROUP BY s.surname, s.forename, s.status, s.staff_id, s.Staff_status,
    g.id, g.cluster_id, 
    gc.cluster_id;    
"""

sqlalchemy.exc.OperationalError: (pymssql.OperationalError) (156, b"Incorrect syntax near the keyword 'INNER'.DB-Lib error message 20018, severity 15:\nGeneral SQL Server error: Check messages from the SQL Server\n") [SQL: 'SELECT DISTINCT s.surname, s.forename, s.status, s.staff_id, s.Staff_status,\n g.id, \n g.cluster_id as g_cluster_id, \n gc.cluster_id as gc_cluster_id \n FROM staff s INNER JOIN local_grant_investigators lgi\n ON s.staff_id = lgi.staff_id \n \t\tGROUP BY s.surname, s.forename, lgi.staff_id\t\t\n\n INNER JOIN grants g\n ON g.id = lgi.grant_id \n INNER JOIN grant_clusters gc\n ON g.id=gc.grant_id\n WHERE s.Staff_status=1\n GROUP BY s.surname, s.forename, s.status, s.staff_id, s.Staff_status,\n g.id, g.cluster_id, \n gc.cluster_id; \n ']

I would appreciate any assistance.

1
Please fix your formatting. Your code is very hard to read. - Tim Biegeleisen
Hi Tim, I updated the code. - Clives-online

1 Answers

0
votes

Your group by line:

GROUP BY s.surname, s.forename, s.status, s.staff_id, s.Staff_status, g.id, g.cluster_id, gc.cluster_id

contains multiple items, thus you can possibly have more than one entry for each surname. So if your group by is simply: GROUP BY s.surname

Then you will get one entry per surname. However I am not sure that is exactly what you are looking for. Your questions is unclear. Do you want one entry per surname or is the error message, the question you want clarified?