mkleehammer / pyodbc

Python ODBC bridge
https://github.com/mkleehammer/pyodbc/wiki
MIT No Attribution
2.94k stars 562 forks source link

pyodbc query doesn't keep GROUP BY order - Microsoft SQL Server #968

Closed redglobuli closed 3 years ago

redglobuli commented 3 years ago

Hi,

i'm trying to get some data from my Microsoft SQL Server.

I expect that the GROUP BY returns assorted data, but i get no sorted output.

OS Linux Python 3.9.7 pyodbc 4.0.32

my script so far:

import pyodbc

server = 'server\server' database = 'Database' username = 'report' password = 'supersecure'

conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server + ';DATABASE=' + database + ';UID=' + username + ';PWD=' + password)

cursor = conn.cursor()

cursor.execute("DECLARE @Date date='01.01.2021';DECLARE @Date2 date='31.01.2021';" "SELECT SUM(ZEF.Hours) AS Sum_Hours, MIT.Name, MIT.Surname FROM ZEF " "INNER JOIN ELMIT ON ZEF.Nr = MIT.Nr " "WHERE ZEF.Date >= @Date AND ZEF.Date <= @Date2 " "GROUP BY MIT.Name, MIT.Surname")

results = cursor.fetchall()

for row in results: print("Name: {}, Surname: {}, Hours: {}".format(row[1], row[2],row[0]))

keitherskine commented 3 years ago

GROUP BY does not return sorted data (in any flavour of SQL), but it's easy enough to add an ORDER BY clause to your code to do that, e.g.:

cursor.execute("DECLARE @Date date='01.01.2021';DECLARE @date2 date='31.01.2021';"
"SELECT SUM(ZEF.Hours) AS Sum_Hours, MIT.Name, MIT.Surname FROM ZEF "
"INNER JOIN ELMIT ON ZEF.Nr = MIT.Nr "
"WHERE ZEF.Date >= @Date AND ZEF.Date <= @date2 "
"GROUP BY MIT.Name, MIT.Surname "
"ORDER BY MIT.Name, MIT.Surname")
redglobuli commented 3 years ago

ah thanks for the answer, i thought it does, as i was trying the same query in Microsoft Report Builder on windows and there it outputs ordered data.

ORDER BY does the trick indeed.