sql函数使用列作为参数

时间:2014-01-21 16:49:06

标签: sql sql-server function

我尝试编写一个使用列作为参数的函数。但是,它没有用。我想知道如何解决它。谢谢。

CREATE FUNCTION dbo.tempMedian(@SCORE INT)
RETURNS @tempTable TABLE
(
    onetcode VARCHAR(20), 
    SCORE INT
)
AS 
BEGIN
    WITH median(onetcode, SCORE, RowNum, loc_total) AS
    (
        SELECT onetcode,
        @SCORE,
        ROW_NUMBER() OVER (PARTITION BY onetcode ORDER BY @SCORE), --ORDER SCORE AND ASSIGN ROW NUMBER
        COUNT(onetcode) OVER (PARTITION BY onetcode) --TOTAL NUMBER OF CASES
        FROM t AS c
)

INSERT @tempTable 
SELECT onetcode, AVG(@SCORE) avgAGW
FROM median
WHERE RowNum BETWEEN (loc_total + 1)/2 AND (loc_total+ 2)/2
GROUP BY onetcode
    RETURN
END;
GO

2 个答案:

答案 0 :(得分:0)

使用CASE声明

...
ROW_NUMBER() OVER (
  PARTITION BY [onetcode]
  ORDER BY
    CASE @SCORE --Choose sorting column
      WHEN 1 THEN [Column1]
      WHEN 2 THEN [Column2]
      ELSE        [Column3]
    END
)
...

答案 1 :(得分:0)

这是最终查询,对我有用。感谢您的投入。

CREATE FUNCTION dbo.tempMedian(@col INT)
RETURNS @tempTable TABLE
(
    onetcode VARCHAR(50), 
    SCORE FLOAT
)
AS 
BEGIN
    WITH median(onetcode, SCORE, RowNum, loc_total) AS
(

    SELECT onetcode,
    CASE @col
        WHEN 1 THEN A
        WHEN 2 THEN C
        ELSE O
    END,
    ROW_NUMBER() OVER (PARTITION BY onetcode 
    ORDER BY 
        CASE @col --Choose sorting column
            WHEN 1 THEN A
            WHEN 2 THEN C
            ELSE O
        END ), --ORDER SCORE AND ASSIGN ROW NUMBER
    COUNT(onetcode) OVER (PARTITION BY onetcode) --TOTAL NUMBER OF CASES
    FROM dbo.PCIInfoSingleScore131230AfterCleaning AS c
)

INSERT @tempTable 
SELECT onetcode, AVG(SCORE) AS median
FROM median
WHERE RowNum BETWEEN (loc_total + 1)/2 AND (loc_total+ 2)/2
GROUP BY onetcode
RETURN
END;
GO