Can the script for median be generalised and put into a function type structure

拟墨画扇 提交于 2019-12-24 20:33:07

问题


We are using the following script to calculate the median:

SELECT 
        [Period] = 'amountPeriodA',             
        [Median] = AVG(x.amountPeriodA)         
INTO    #mediantable
FROM (
        SELECT 
                r.customer,
                r.amountPeriodA,
                [RowASC] = ROW_NUMBER() OVER(ORDER BY r.amountPeriodA ASC, customer ASC),
                [RowDESC] = ROW_NUMBER() OVER(ORDER BY r.amountPeriodA DESC, customer DESC)
        FROM #MyExample r 
    ) x
WHERE RowASC IN (RowDESC, ROWDESC-1, ROWDESC+1)

Is it possible to generalise a script like this and then code it into the server so that in the future we just have to specify the respective table & columns as parameters and the structure returns the Median ?


回答1:


I think what you need is a stored procedure. It's good when you execute the same query many times with different parameters.

Here's a good tutorial about stored procedures on SQL SERVER

A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and over again.



来源:https://stackoverflow.com/questions/12821532/can-the-script-for-median-be-generalised-and-put-into-a-function-type-structure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!