Как сделать запрос, чтобы получить разницу столбцов между двумя последующими строками - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь получить разницу между столбцом строки и столбцом следующей строки. Например:

 pk | hour  | ts 
----+-------+----
  1 | 10:30 | 0
  2 | 10:50 | 20
  3 | 11:00 | 10

Где ts - это разница между hour столбцом между следующим элементом и текущим

Я не знаю Я не хочу получить все объекты, а затем сделать это, используя python, потому что на производстве будет много строк, и я слышал, что это становится неэффективным.

Итак, я попробовал несколько способов.

Опция 1 - Использование raw sql с LAG:

Computer.objects.raw('''
    SELECT id, hostname, date, date - LAG (date) OVER (ORDER BY date) AS lagged FROM hub_computer
''')

При доступе к элементу выдается следующая ошибка:

Traceback (most recent call last):
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: near "(": syntax error

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1461, in __getitem__
    return list(self)[k]
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1421, in __iter__
    self._fetch_all()
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1408, in _fetch_all
    self._result_cache = list(self.iterator())
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1431, in iterator
    query = iter(self.query)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 109, in __iter__
    self._execute_query()
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/sql/query.py", line 143, in _execute_query
    self.cursor.execute(self.sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: near "(": syntax error

Опция 2 - Использование django оконной функции Lag():

Computer.objects.annotate(diff=F('date')-Lag('date'))

При работе выдает следующую ошибку:

Traceback (most recent call last):
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such function: LAG

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 252, in __repr__
    data = list(self[:REPR_OUTPUT_SIZE + 1])
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 276, in __iter__
    self._fetch_all()
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 1261, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/query.py", line 57, in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1144, in execute_sql
    cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
    return super().execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "/home/rickerp/.local/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such function: LAG

Я искал целое число rnet, там мало информации об этом и о том, как использовать django Lag() функцию

Я был бы рад, если бы кто-нибудь мог мне помочь

С наилучшими пожеланиями, Риккерп

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...