Reputation: 1
I am trying to get a column which specify the points by comparing the value from original table to min and max value from another table. I have a main table, which consists of few columns of values and the respective point column to be inserted. Here is the example:
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 |
--------------------------------------------------------------------------------
Department and BU need to match and the RevenuePoint needs to take the records where the Category = Revenue, same as ProfitPoint.
I tried a few ways that i found in here, but most not as complex as mine so i have no idea how to move from here.
This is the code that i tried
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
Upvotes: 0
Views: 40