我正在使用SQL Server 2014,并且具有以下T-SQL查询来计算中值。但是,我希望我的中位语法(Percentile_cont)在执行计算时排除零。我该怎么办?
CREATE TABLE #MyTempTable (Id int, Market nvarchar(50), [F&B] numeric (19,4) , SPA numeric (19,4))
INSERT INTO #MyTempTable
VALUES
(200, 'UK', 200, 0),
(210, 'UK', 150, 300),
(236, 'FRANCE', 60, 450),
(237, 'FRANCE', 120, 0),
(265, 'UK', 400, 100),
(270, 'FRANCE', 0, 140)
SELECT
DISTINCT [Market],
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ([F&B])) OVER (PARTITION BY [Market]) AS 'MEDIAN_F&B',
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY ([SPA])) OVER (PARTITION BY [Market]) AS 'MEDIAN_SPA'
FROM #MyTempTable
当前输出:
Market MEDIAN_F&B MEDIAN_SPA
FRANCE 60 140
UK 200 100
预期输出:
答案 0 :(得分:2)
只需使用条件:
SELECT DISTINCT [Market],
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY NULLIF([F&B], 0)) OVER (PARTITION BY [Market]) AS [MEDIAN_F&B],
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY NULLIF([SPA], 0)) OVER (PARTITION BY [Market] AS [MEDIAN_SPA]
FROM #MyTempTable ;
PERCENTILE
函数将忽略NULL
值,因此这应该是最简单的方法。
答案 1 :(得分:1)
尝试
ValueError: setting an array element with a sequence.