# Buggy code
def get_result(doc, to_date=None):
    doc = frappe.parse_json(doc)
    fields = []
    sql_function_map = {
        "Count": "count",
        "Sum": "sum",
        "Average": "avg",
        "Minimum": "min",
        "Maximum": "max",
    }

    function = sql_function_map[doc.function]

    if function == "count":
        fields = ["{function}(*) as result".format(function=function)]
    else:
        fields = [
            "{function}({based_on}) as result".format(
                function=function, based_on=doc.aggregate_function_based_on
            )
        ]

    filters = frappe.parse_json(doc.filters_json)

    if to_date:
        filters.append([doc.document_type, "creation", "<", to_date, False])

    res = frappe.db.get_all(doc.document_type, fields=fields, filters=filters)
    number = res[0]["result"] if res else 0

    frappe.db.set_value("Number Card", doc.name, "previous_result", number)
    return number


# Traceback (pymysql.err.InternalError)
Traceback (most recent call last):
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/app.py", line 62, in application
19:47:45 web.1            |     response = frappe.api.handle()
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/api.py", line 58, in handle
19:47:45 web.1            |     return frappe.handler.handle()
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/handler.py", line 24, in handle
19:47:45 web.1            |     data = execute_cmd(cmd)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/handler.py", line 63, in execute_cmd
19:47:45 web.1            |     return frappe.call(method, **frappe.form_dict)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/__init__.py", line 1074, in call
19:47:45 web.1            |     return fn(*args, **newargs)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/desk/doctype/number_card/number_card.py", line 70, in get_result
19:47:45 web.1            |     frappe.db.set_value('Number Card', doc.name, 'previous_result', number)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/database/database.py", line 653, in set_value
19:47:45 web.1            |     values, debug=debug)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/apps/frappe/frappe/database/database.py", line 156, in sql
19:47:45 web.1            |     self._cursor.execute(query, values)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/cursors.py", line 170, in execute
19:47:45 web.1            |     result = self._query(query)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/cursors.py", line 328, in _query
19:47:45 web.1            |     conn.query(q)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/connections.py", line 517, in query
19:47:45 web.1            |     self._affected_rows = self._read_query_result(unbuffered=unbuffered)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/connections.py", line 732, in _read_query_result
19:47:45 web.1            |     result.read()
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in read
19:47:45 web.1            |     first_packet = self.connection._read_packet()
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/connections.py", line 684, in _read_packet
19:47:45 web.1            |     packet.check_error()
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/protocol.py", line 220, in check_error
19:47:45 web.1            |     err.raise_mysql_exception(self._data)
19:47:45 web.1            |   File "/home/frappe/frappe-bench/env/lib/python3.6/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
19:47:45 web.1            |     raise errorclass(errno, errval)
19:47:45 web.1            | pymysql.err.InternalError: (1054, "Unknown column 'previous_result' in 'field list'")

# Fixed code
def get_result(doc, to_date=None):
    doc = frappe.parse_json(doc)
    fields = []
    sql_function_map = {
        "Count": "count",
        "Sum": "sum",
        "Average": "avg",
        "Minimum": "min",
        "Maximum": "max",
    }

    function = sql_function_map[doc.function]

    if function == "count":
        fields = ["{function}(*) as result".format(function=function)]
    else:
        fields = [
            "{function}({based_on}) as result".format(
                function=function, based_on=doc.aggregate_function_based_on
            )
        ]

    filters = frappe.parse_json(doc.filters_json)

    if to_date:
        filters.append([doc.document_type, "creation", "<", to_date, False])

    res = frappe.db.get_all(doc.document_type, fields=fields, filters=filters)
    number = res[0]["result"] if res else 0

    return number