I need to calculate the median transaction amount for each customer in the past 52 weeks, but percentile_cont returns NULL if there's no transaction for a particular customer. In such a case, I have to replace NULL with zero, I acheived this by using a CASE clause in sql, however I am using PERCENTILE_CONT twice for this purpose which makes the query slow for a huge list of customers to process. is there a better way to use the PERCENTILE_CONT only once inside the CASE clause?
SELECT DISTINCT customer,
CASE WHEN
PERCENTILE_CONT(0.5)
WITHIN GROUP (ORDER BY
transamt) OVER
(PARTITION BY
customer) IS NOT NULL THEN
PERCENTILE_CONT(0.5) WITHIN
GROUP (ORDER BY transamt)
OVER (PARTITION BY
customer)
ELSE 0
END AS median_amt
FROM trans_table
WHERE trans_date BETWEEN DATEADD(WEEK, -52, GETDATE() ) AND GETDATE()