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 / 307794
Accepted
IBot
IBot
Asked: 2022-02-22 15:57:58 +0800 CST2022-02-22 15:57:58 +0800 CST 2022-02-22 15:57:58 +0800 CST

GROUP BY coluna de data e, em seguida, agrupe por dia personalizado

  • 772

Então eu tenho que agrupar uma tabela de acordo com a data e depois o dia de chegada de um produto, os dias de hora seriam:

morning = [5, 6, 7 , 8, 9]
mid_morning = [10, 11]
midday = [12, 13, 14]
evening = [15, 16, 17 ,18 ,19, 20]
night = [21, 22, 23, 0, 1, 2, 3, 4]

Esta é a tabela:

 CREATE TABLE inventory (
      inventory_id serial PRIMARY KEY,
      arrive_date date NOT NULL,
      arrive_location character varying NOT NULL,
      thing_type integer NOT NULL,
      quantity integer NOT NULL
    );

INSERT INTO inventory (arrive_date, arrive_location, thing_type, quantity) VALUES
  ('2018-05-30 05:00:00-00', 'location_00', 3, 2)
, ('2018-05-30 06:00:00-00', 'location_00', 3, 8)
, ('2018-05-30 12:50:00-00', 'location_00', 5, 2)
, ('2018-05-30 13:40:00-00', 'location_00', 1, 3)
, ('2018-05-31 13:00:00-00', 'location_00', 4, 7)
, ('2018-05-31 18:00:00-00', 'location_00', 2, 3)
;

O resultado desejado seria ter este resultado da tabela:

preprocess_id data_chegada chegar_horadia chegar_local dados
33 30-05-2018 0 localização_00 { "3": 10}
34 30-05-2018 2 localização_00 { "5": 2, "1": 3 }
36 31-05-2018 2 localização_00 { "4": 7 }
37 31-05-2018 4 localização_00 { "2": 3 }

O violino de consulta atual que tenho apenas agrupar por dia, é possível ter a data e depois o dia?

group-by postgresql-13
  • 1 1 respostas
  • 119 Views

1 respostas

  • Voted
  1. Best Answer
    Fat P
    2022-02-22T20:07:55+08:002022-02-22T20:07:55+08:00

    Eu não entendo como preprocess_idfoi produzido e como uma hora real foi mapeada para arrive_timedayo resultado desejado. De qualquer forma, você pode usar uma CASEexpressão ou uma tabela de mapeamento para mapear o número.

    Usando CASEexpressão

    SELECT arrive_date, arrive_timeday, arrive_location
         , jsonb_object_agg(thing_type, total_things)
    FROM  (
       SELECT arrive_date
            , arrive_timeday
            , arrive_location
            , thing_type
            , sum(quantity) AS total_things
       FROM   (
           SELECT date_trunc('day', arrive_date) AS arrive_date
                , case 
                  when extract(hour from arrive_date) in (5, 6, 7 , 8, 9) then 0
                  when extract(hour from arrive_date) in (10, 11) then 1
                  when extract(hour from arrive_date) in (12, 13, 14) then 2
                  when extract(hour from arrive_date) in (15, 16, 17 ,18 ,19, 20) then 4
                  when extract(hour from arrive_date) in (21, 22, 23, 0, 1, 2, 3, 4) then 8
                  end arrive_timeday
                , arrive_location
                , thing_type
                , quantity
           FROM   inventory
       ) inv
       GROUP  BY arrive_date, arrive_timeday, arrive_location, thing_type
       ) sub
    GROUP  BY arrive_date, arrive_timeday, arrive_location
    ORDER  BY arrive_date, arrive_timeday, arrive_location;
    

    Usando a tabela de mapeamento:

    Criação da tabela:

    CREATE TABLE hour_mapping (
      hour_from integer NOT NULL,
      hour_to integer NOT NULL,
      timeday integer NOT NULL,
      descpt character varying NOT NULL
    );
    
    INSERT INTO hour_mapping (hour_from, hour_to, timeday, descpt) VALUES 
      (5, 9, 0, 'morning')
    , (10, 11, 1, 'mid_morning')
    , (12, 14, 2, 'midday')
    , (15, 20, 4, 'evening')
    , (21, 23, 8, 'night')
    , (0, 4, 8, 'night')
    ;
    

    Consulta

    SELECT arrive_date, arrive_timeday, arrive_location
         , jsonb_object_agg(thing_type, total_things)
    FROM  (
       SELECT date_trunc('day', arrive_date) AS arrive_date
            , m.timeday as arrive_timeday
            , arrive_location
            , thing_type
            , sum(quantity) AS total_things
       FROM  inventory inv, hour_mapping m
       WHERE extract(hour from inv.arrive_date) between m.hour_from and hour_to
       GROUP  BY arrive_date, arrive_timeday, arrive_location, thing_type
       ) sub
    GROUP  BY arrive_date, arrive_timeday, arrive_location
    ORDER  BY arrive_date, arrive_timeday, arrive_location;
    

    violino

    • 1

relate perguntas

  • Finalidade T-SQL do MAX neste grupo por consulta

  • Como agrupar com min(date) e selecionar outra coluna na mesma tabela

  • GROUP BY em um campo dependente

  • limitar e depois agrupar no MySQL

  • Agrupamento de estoque em intervalos de 6 meses

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