SELECT
C.category_name,
P.product_name,
SUM(P.unit_price) as unit_price,
ROUND(
AVG(P.unit_price) OVER(partition by C.category_name) :: numeric,
2
) AS avg_unit_price,
ROUND(
(
(
MAX(P.unit_price) OVER(partition by C.category_name) + MIN(P.unit_price) OVER(partition by C.category_name)
) / 2
) :: numeric,
2
) AS median_unit_price,
CASE
WHEN SUM(P.unit_price) < (
AVG(P.unit_price) OVER(partition by C.category_name)
) THEN 'BELOW AVERAGE'
WHEN SUM(P.unit_price) > (
AVG(P.unit_price) OVER(partition by C.category_name)
) THEN 'OVER AVERAGE'
WHEN SUM(P.unit_price) = (
AVG(P.unit_price) OVER(partition by C.category_name)
) THEN 'AVERAGE'
END AS avg_unit_price,
CASE
WHEN SUM(P.unit_price) < (
(
MAX(P.unit_price) OVER(partition by C.category_name) + MIN(P.unit_price) OVER(partition by C.category_name)
) / 2
) THEN 'BELOW MEDIAN'
WHEN SUM(P.unit_price) > (
(
MAX(P.unit_price) OVER(partition by C.category_name) + MIN(P.unit_price) OVER(partition by C.category_name)
) / 2
) THEN 'OVER MEDIAN'
WHEN SUM(P.unit_price) = (
(
MAX(P.unit_price) OVER(partition by C.category_name) + MIN(P.unit_price) OVER(partition by C.category_name)
) / 2
) THEN 'MEDIAN'
END AS median_unit_price
FROM
products as P
JOIN categories as C USING(category_id)
WHERE
P.discontinued = 0
GROUP BY
P.product_name,
C.category_name,
p.unit_price
ORDER BY
C.category_name ASC,
C.category_name ASC;
in above query I have used this window function to get median
(MAX(P.unit_price) OVER(partition by C.category_name) + MIN(P.unit_price) OVER(partition by C.category_name)) / 2
Which I have later used in CASE statement for comparison, I need to copy paste same code over and over again is there a positble solution for this? I did some reasearch, didnot help as I am new to postgres ,so I need help.