I want to select max prices only when certain condition on the table are met. The table consist of this column
| id | product_item_code | distribution_channel | sap_no_shipto | valuation_type | price |
|----|-------------------|----------------------|---------------|----------------|-------|
| 1 | A | A | A | NULL | 200 |
| 2 | A | A | A | B | 2000 |
| 3 | A | A | A | C | 3000 |
I want to apply this logic
- If the
valuation_type
are NULL use theprice
from that row - If the
valuation_type
are not null, use the highest price
Table have unique constrain combination
product_item_code | distribution_channel | sap_no_shipto | valuation_type
For now, I code it like this, but it doesn’t satisfy the first condition.
Below are the subquery. Is there any way to apply the logic? Because this query only select the MAX price if there are null
on valuation type, it will ignore it.
SELECT MAX(psp.price)
FROM product_special_prices psp
WHERE
psp.product_item_code = p.item_code AND
psp.distribution_channel = st.distribution_channel AND
psp.sap_no_shipto = st.sap_no_shipto
GROUP BY (
psp.product_item_code,
psp.distribution_channel,
psp.sap_no_shipto
)
3
Answers
You can order by price and take the highest:
This will sort the rows with
valuation_type
of value NULL first, becauseFALSE < TRUE
.DISTINCT ON
will return the first row for each group.Another option, you could use the
coalesce
and filtered max function as the following:Demo
Try with this
SELECT *
,NewColumn = CASE WHEN valuation_type IS NOT NULL THEN tb.price ELSE tb2.PriceMax END
FROM table tb
OUTER APPLY (
SELECT PriceMax = MAX(price) FROM table
) tb2