问题
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