Skip to content

Instantly share code, notes, and snippets.

@mburbea
Last active March 22, 2022 00:38
Show Gist options
  • Save mburbea/52d6e4971f4eabea4c37abb0976231ff to your computer and use it in GitHub Desktop.
Save mburbea/52d6e4971f4eabea4c37abb0976231ff to your computer and use it in GitHub Desktop.
/*
drop table if exists #data
select min,max, value = 1e* (abs(binary_checksum(newid()))%1000)
into #data
from (values(0, 9)
,(10, 19)
,(20, 29)
,(30, 39)
,(40, 59)
,(60, 70)
,(70, null)) d(min,max)
*/
select * from #data
select *
,median = max(iif(sign(midp - rsum) < sign(midp - rsum + value) then min + ((midp - rsum + value) / nullif(value, 0)) * (max - min),null)) over()
from (
select min,
max,
value,
rsum = sum(value) over (order by min rows unbounded preceding),
midp = sum(value) over () / 2
from #data d
) z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment