whatsnew 2.4 about itertools.groupby:

G?nter Jantzen guenter.jantzen at t-mobile.de
Wed Jun 9 07:00:58 EDT 2004


In the documentation
http://www.python.org/dev/doc/devel/whatsnew/node7.html  is written
about itertools.groupby:

"""Like it SQL counterpart, groupby() is typically used with sorted
input."""

In SQL queries is the groupby clause not related to 'input order'.
This notion makes not much sense in SQL context.
SQL is based on relational Algebra. A SQL- table is based on an
unordered set of rows (implementation can be different, of course).

So the analogon of
----------------------
>>> import itertools
>>> L = [2,4,6, 7,8,9,11, 12, 14]
>>> for key_val, it in itertools.groupby(L, lambda x: x % 2):
...    print key_val, list(it)
... 
0 [2, 4, 6]
1 [7]
0 [8]
1 [9, 11]
0 [12, 14]
>>>
------------------------

Say you have a table 'example' with only one column 'i'

_________________________
select * from example; 

I                                       
----
2                                       
14                                       
6                                       
7                                       
8                                       
9                                       
11                                      
12                                      
4                                      
___________________________

the order of rows is not defined

Then you can group this table

____________________________________________
select count(i), mod(i,2) from example group by mod(i,2)


COUNT(I) | MOD(I,2)
---------+---------
6        | 0       
3        | 1       
___________________________________________

The result dos not depend on 'input order' or 'runs'



More information about the Python-list mailing list