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 / 331784
Accepted
John Marston
John Marston
Asked: 2023-10-03 10:14:28 +0800 CST2023-10-03 10:14:28 +0800 CST 2023-10-03 10:14:28 +0800 CST

Obtenha pontos de outra tabela com base na categoria e faixa de valores

  • 772

Estou tentando obter uma coluna que especifique os pontos comparando o valor da tabela original com os valores mínimo e máximo de outra tabela. Tenho uma tabela principal, que consiste em algumas colunas de valores e a respectiva coluna de pontos a serem inseridos. Aqui está o exemplo:

Main table
--------------------------------------------------------------------------------
| User   | Department |  BU  |  Revenue | Revenuepoint | Profit |  Profitpoint |
--------------------------------------------------------------------------------
| A      | 1000000    | 101  |  400     |              | 200    |              |
| B      | 1000001    | 101  |  300     |              | 100    |              |
| C      | 1000000    | 102  |  350     |              | 150    |              |
--------------------------------------------------------------------------------


Point table
----------------------------------------------------------------
| Category| Department |  BU  |  Fromvalue  | Tovalue | Point  |
----------------------------------------------------------------
| Revenue | 1000000    | 101  |  0          | 200     | 1      |
| Revenue | 1000000    | 101  |  201        | 400     | 2      |
| Revenue | 1000000    | 102  |  0          | 300     | 1      |
| Revenue | 1000000    | 102  |  301        | 400     | 2      |
| Revenue | 1000001    | 101  |  0          | 200     | 1      |
| Revenue | 1000001    | 101  |  201        | 400     | 2      |
| Profit  | 1000000    | 101  |  0          | 100     | 1      |
| Profit  | 1000000    | 101  |  101        | 300     | 2      |
| Profit  | 1000000    | 102  |  0          | 50      | 1      |
| Profit  | 1000000    | 102  |  51         | 200     | 2      |
| Profit  | 1000001    | 101  |  0          | 50      | 1      |
| Profit  | 1000001    | 101  |  51         | 200     | 2      |
----------------------------------------------------------------


Expected table
--------------------------------------------------------------------------------
| User   | Department |  BU  |  Revenue | Revenuepoint | Profit |  Profitpoint |
--------------------------------------------------------------------------------
| A      | 1000000    | 101  |  400     |       2      | 200    |       2      |
| B      | 1000001    | 101  |  300     |       2      | 40     |       1      |
| C      | 1000000    | 102  |  350     |       2      | 150    |       2      |
--------------------------------------------------------------------------------

Departamento e BU precisam corresponder e o RevenuePoint precisa pegar os registros onde Categoria = Receita, igual ao ProfitPoint.

Tentei algumas maneiras que encontrei aqui, mas a maioria não é tão complexa quanto a minha, então não tenho ideia de como sair daqui.

Este é o código que eu tentei

SELECT 
a.User, 
a.Department, 
a.BU, 
a.Revenue, 
(SELECT MAX(b.Point) from Point b WHERE a.Revenue BETWEEN b.fromvalue and b.tovalue) as Revenuepoint,
b.Point as Revenuepoint,
a.Profit, 
(SELECT MAX(b.Point) from Point b WHERE a.Profit BETWEEN b.fromvalue and b.tovalue) as Profitpoint
FROM Sales a
sql-server
  • 1 1 respostas
  • 33 Views

1 respostas

  • Voted
  1. Best Answer
    Caleb Carl
    2023-11-07T08:24:40+08:002023-11-07T08:24:40+08:00

    CROSS APPLY uma tabela PIVOT -

    Documentação do MSDN aqui - https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-ver16

    Preenchi seus dados usando este código -

    CREATE TABLE #sales
    (
        [User] CHAR(1)
      , Department INT
      , BU INT
      , Revenue INT
      , RevenuePoint INT
      , Profit INT
      , ProfitPoint INT
    );
    
    INSERT INTO #sales
    VALUES
    ('A', 1000000, 101, 400, NULL, 200, NULL)
    , ('B', 1000001, 101, 300, NULL, 100, NULL)
    , ('C', 1000000, 102, 350, NULL, 150, NULL);
    
    CREATE TABLE #point
    (
        Category VARCHAR(10)
      , Department INT
      , BU INT
      , FromValue INT
      , ToValue INT
      , Point INT
    );
    
    INSERT INTO #point
    VALUES
    ('Revenue', 1000000, 101, 0, 200, 1)
    , ('Revenue', 1000000, 101, 201, 400, 2)
    , ('Revenue', 1000000, 102, 0, 300, 1)
    , ('Revenue', 1000000, 102, 301, 400, 2)
    , ('Revenue', 1000001, 101, 0, 200, 1)
    , ('Revenue', 1000001, 101, 201, 400, 2)
    , ('Profit', 1000000, 101, 0, 100, 1)
    , ('Profit', 1000000, 101, 101, 300, 2)
    , ('Profit', 1000000, 102, 0, 50, 1)
    , ('Profit', 1000000, 102, 51, 200, 2)
    , ('Profit', 1000001, 101, 0, 50, 1)
    , ('Profit', 1000001, 101, 51, 200, 1);
    

    Então, ao executar isso, você obtém o conjunto de dados desejado -

    SELECT s.[User]
         , s.Department
         , s.BU
         , s.Revenue
         , display.Revenue
         , s.Profit
         , display.Profit
    FROM #sales AS s
        CROSS APPLY
    (
        SELECT p_pvt.Profit
             , p_pvt.Revenue
        FROM
        (
            SELECT p.Category
                 , p.Point
            FROM #point AS p
            WHERE s.Department = p.Department
                  AND s.BU = p.BU
                  AND
                  (
                      (
                          s.Revenue
                  BETWEEN p.FromValue AND p.ToValue
                          AND p.Category = 'Revenue'
                      )
                      OR
                      (
                          s.Profit
                  BETWEEN p.FromValue AND p.ToValue
                          AND p.Category = 'Profit'
                      )
                  )
        ) AS p_root
        PIVOT
        (
            MAX(Point)
            FOR Category IN (Revenue, Profit)
        ) AS p_pvt
    ) AS display;
    

    A instrução UPDATE ficaria assim -

    UPDATE s
    SET s.RevenuePoint = display.Revenue
      , s.ProfitPoint = display.Profit
    FROM #sales AS s
        CROSS APPLY
    (
        SELECT p_pvt.Profit
             , p_pvt.Revenue
        FROM
        (
            SELECT p.Category
                 , p.Point
            FROM #point AS p
            WHERE s.Department = p.Department
                  AND s.BU = p.BU
                  AND
                  (
                      (
                          s.Revenue
                  BETWEEN p.FromValue AND p.ToValue
                          AND p.Category = 'Revenue'
                      )
                      OR
                      (
                          s.Profit
                  BETWEEN p.FromValue AND p.ToValue
                          AND p.Category = 'Profit'
                      )
                  )
        ) AS p_root
        PIVOT
        (
            MAX(Point)
            FOR Category IN (Revenue, Profit)
        ) AS p_pvt
    ) AS display;
    

    A tabela de resultados é a seguinte -

    User Department  BU          Revenue     RevenuePoint     Profit      ProfitPoint
    ---- ----------- ----------- ----------- ----------- ----------- -----------
    A    1000000     101         400         2           200         2
    B    1000001     101         300         2           100         1
    C    1000000     102         350         2           150         2
    
    • 0

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

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