如何将NTILE函数应用于SQL列

时间:2019-01-08 12:39:39

标签: sql sql-server tsql

因此,我试图根据某些客户获得的关注程度建立分位数,但是在应用NTILES函数之前,将NULL和0留在样本中,并将它们分别置于0和null分位数中,正在使用此功能:

CREATE FUNCTION dbo.RPS_Ntiles (@data int,@percentil int)  
RETURNS TABLE
AS
RETURN 
SELECT 
  NTILE(@percentil) OVER(ORDER BY @data DESC) as QUINTIL
  WHERE @data > 0
UNION
SELECT
CASE 
    WHEN CONVERT(int,@data) = 0 THEN 0
    WHEN @data is NULL THEN NULL
    END AS QUINTIL
WHERE @data = 0 or @data = NULL 

然后我将使用CROSS APPLY进行应用

SELECT t.QUINTIL,D.[atenciones]
FROM table as D
CROSS APPLY [dbo].[RPS_NTiles](CONVERT(int,D.[atenciones]),5) as t
ORDER BY D.[atenciones] DESC

此查询的结果可以有效地使NTILEs函数中的值为0和null,但其余数据则完全像这样放置在1个quintil中:

+------------+---------+--+
| Atenciones | Quintil |  |
+------------+---------+--+
|         0  |       0 |  |
|         0  |       0 |  |
|       NULL |    NULL |  |
|         1  |       1 |  |
|         3  |       1 |  |
|         4  |       1 |  |
|         7  |       1 |  |
|        46  |       1 |  |
|        59  |       1 |  |
+------------+---------+--+

我正在寻找这样的东西:

+------------+---------+--+
| Atenciones | Quintil |  |
+------------+---------+--+
|         0  |       0 |  |
|         0  |       0 |  |
|       NULL |    NULL |  |
|         1  |       1 |  |
|         3  |       2 |  |
|         4  |       2 |  |
|         7  |       3 |  |
|        46  |       4 |  |
|        59  |       5 |  |
+------------+---------+--+

1 个答案:

答案 0 :(得分:1)

为什么要定义自己的功能?您可以使用case逻辑表达这一点:

select (case when Atenciones is null or Atenciones = 0
             then Atenciones
             else ntile(5) over (partition by (case when Atenciones is null or Atenciones = 0 then 1 else 2 end)
                                 order by Atenciones
                                ) 
        end)