AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 336080
Accepted
Ashley
Ashley
Asked: 2024-02-21 11:52:14 +0800 CST2024-02-21 11:52:14 +0800 CST 2024-02-21 11:52:14 +0800 CST

Selecione registros aleatórios até que um total cumulativo seja excedido

  • 772

Eu tenho uma tabela de vídeos com uma coluna e ide estou tentando escrever uma consulta que retornará uma lista de reprodução de vídeos distintos com duração total superior a .skill_leveldurationX

select _id, duration, running_total
from (select *, sum(duration) over (order by RANDOM()) as running_total
      from videos
      where skill_level in ('beginner', 'superbeginner') AND watched IS NULL
     )
where running_total <= 7200;

Isso funciona e retorna o seguinte:

5e4d11fbaac87f3820954c45|305|305
64e51ad279223a9ad03525c2|930|1235
5e4d1204aac87f3820954c64|627|1862
5e4d1212aac87f3820954c95|367|2229
641e05c2d7c1512d278dc51a|361|2590
5e4d1200aac87f3820954c57|444|3034
649aa7089776ba12d8de28d5|329|3363
5e4d123eaac87f3820954d2c|573|3936
5e4d1216aac87f3820954ca1|399|4335
5e4d120daac87f3820954c84|315|4650
5e4d11dfaac87f3820954be1|510|5160
64f7036d3d578af923ba2afc|326|5486
5e4d11fcaac87f3820954c47|437|5923
5fa51afc27a912152cc51c33|1062|6985

Mas, idealmente, quero retornar registros suficientes para exceder, Xmas apenas um. 6375274c1cff4a7e31b04a0dabaixo nos coloca 7200.

5e4d11fbaac87f3820954c45|305|305
64e51ad279223a9ad03525c2|930|1235
5e4d1204aac87f3820954c64|627|1862
5e4d1212aac87f3820954c95|367|2229
641e05c2d7c1512d278dc51a|361|2590
5e4d1200aac87f3820954c57|444|3034
649aa7089776ba12d8de28d5|329|3363
5e4d123eaac87f3820954d2c|573|3936
5e4d1216aac87f3820954ca1|399|4335
5e4d120daac87f3820954c84|315|4650
5e4d11dfaac87f3820954be1|510|5160
64f7036d3d578af923ba2afc|326|5486
5e4d11fcaac87f3820954c47|437|5923
5fa51afc27a912152cc51c33|1062|6985
6375274c1cff4a7e31b04a0d|1138|8123

É possível escrever uma consulta para conseguir isso no sqlite?

query
  • 1 1 respostas
  • 13 Views

1 respostas

  • Voted
  1. Best Answer
    White Owl
    2024-02-21T22:42:12+08:002024-02-21T22:42:12+08:00

    Em outras palavras, a tarefa é obter uma lista de registros com uma soma menor que o limite e um registro adicional para ultrapassar o limite?

    Isso pode ser conseguido usando cláusulas withe union:

    with
    below_threshold as (
      select _id, duration, running_total
      from (select *, sum(duration) over (order by RANDOM()) as running_total
            from videos
            where skill_level in ('beginner', 'superbeginner') AND watched IS NULL
           )
      where running_total <= 7200
    ),
    one_more as (
      select _id, duration
      from videos
      where skill_level in ('beginner', 'superbeginner') AND watched IS NULL
            and _id not in (select _id from below_threshold)
      limit 1
      order by random()
    )
    select _id, duration from below_threshold
    union
    select _id, duration from one_more
    

    ou você pode fazer uma pré-seleção:

    with
    to_consider as (
      select _id, duration
      from videos
      where skill_level in ('beginner', 'superbeginner') AND watched IS NULL
    ),
    below_threshold as (
      select _id, duration, running_total
      from (select *, sum(duration) over (order by RANDOM()) as running_total
            from to_consider
           )
      where running_total <= 7200
    ),
    one_more as (
      select _id, duration, (select sum(duration) from below_threshold)+duration as running_total
      from to_consider
      where _id not in (select _id from below_threshold)
      limit 1
      order by random()
    )
    select _id, duration, running_total from below_threshold
    union
    select _id, duration, running_total from one_more
    
    • 1

relate perguntas

  • Consultar a tabela PostgreSQL 9.0 no valor da chave estrangeira?

  • Como obter os nomes dos amigos de um usuário?

  • Consulta entre duas tabelas relacionadas

  • Alinhamento de data e extração de par correspondente melhor feito com TSQL ou C #?

  • LIKE para selecionar a existência independente da palavra em qualquer parte do texto

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve