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
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 -
Então, ao executar isso, você obtém o conjunto de dados desejado -
A instrução UPDATE ficaria assim -
A tabela de resultados é a seguinte -