I have a query below that gives me median, I want to put my count(*) that counts the total # of rows that I use in my median calculation in a seperate subquery (since it runs a bit better that way). What is the best way to do that? Thank you!
SELECT our_id, AVG(1.0 * our_val) as Median
FROM
( SELECT our_id, our_val,
COUNT(*) OVER (PARTITION BY our_id) AS cnt,
ROW_NUMBER() OVER (PARTITION BY our_id ORDER BY our_val) AS rn
FROM our_table
) AS x
WHERE rn IN ((cnt + 1)/2, (cnt + 2)/2) GROUP BY our_id;
You are calculating count(*)
in the subquery. Why not just use that?
SELECT our_id, AVG(1.0 * our_val) as Median, cnt
FROM (SELECT our_id, our_val,
COUNT(*) OVER (PARTITION BY our_id) AS cnt,
ROW_NUMBER() OVER (PARTITION BY our_id ORDER BY our_val) AS rn
FROM our_table
) x
WHERE rn IN ((cnt + 1)/2, (cnt + 2)/2)
GROUP BY our_id, cnt;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.