Tech Qu: Find the Median/Percentile value of a table
Everyone knows how to find the average of a column, asking to find a median (technically the 50percentile) in TSQL can be an exercise for some. A simple solution is shown below.
Code Snippet
- DECLARE @Percentile int=50
- DECLARE @PercentileTop int
- DECLARE @PercentileValue money
- SELECT @PercentileTop =count(1)
- FROM [SalesLT].[Product]
- WHERE LISTPRICE IS NOT NULL
- SET @PercentileTop =(@PercentileTop * @Percentile)/100
- SELECT TOP(@PercentileTop)@PercentileValue=[ListPrice]
- FROM [SalesLT].[Product]
- WHERE LISTPRICE IS NOT NULL
- ORDER BY LISTPRICE
- SELECT @PercentileValue
The next question would be to encapsulate this for reuse – I will leave that for people to comment on. Let us see how creative our readers can be!
putting lectures on iPods/iPhones and she was fascinated. I promised to send her details about how to do this.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteThis comment has been removed by a blog administrator.
ReplyDeleteThanks for sharing this code! I've used all discounts by Edusson and have no other possibility to hire someone to help me with coding.
ReplyDelete