MySQL select “accumulated” column

前端 未结 4 983
故里飘歌
故里飘歌 2020-12-16 23:30

I\'m not sure what to call this besides an \"accumulated\" column.

I have a MySQL table with a column that looks like

+---+
|val|
+---+
| 1 |
| 4 |
|         


        
4条回答
  •  再見小時候
    2020-12-16 23:40

    I would use a cursor:

    >>> import MySQLdb
    >>> db = MySQLdb.connect("localhost","username","password","test")
    >>> cur = db.cursor()
    >>> cur.execute("select myval from mytable")
    >>> rs = cur.fetchall()
    >>> accumulator = 0
    >>> for r, in rs:
    ...   accumulator += r
    ...   print r, accumulator
    ...
    1 1
    4 5
    6 11
    3 14
    2 16
    5 21
    

提交回复
热议问题