SELECT [Cole_Crops],
PERCENT_RANK() OVER (PARTITION BY HUC02
ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
[Row_Crops],
PERCENT_RANK() OVER (PARTITION BY HUC02
ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09
如何在具有多个要排名的列的查询中排除NULL值以影响PERCENT_RANK?
SQL Server 2012 PERCENT_RANK()
将NULLS视为分发中的实际值。如果有一列要排名,您只需添加一个where子句(即where Cole_Crops IS NOT NULL
)。
答案 0 :(得分:1)
这是一个简单的修复,在你的分区子句中使用case语句。
CASE
WHEN COLUMN_1 IS NULL THEN NULL
ELSE PERCENT_RANK() OVER
(PARTITION BY
CASE
WHEN COLUMN_1 IS NULL THEN 0
ELSE 1
END
ORDER BY COLUMN_1)
END AS RANK_COLUMN_1
这将分别对空值和非空值进行排名,但包装案例语句将空值显示为空值。
问题解决了!
答案 1 :(得分:0)
您可以在Percent_Rank ORDER BY中使用case语句。您可以根据需要创建NULL值。下面是将所有NULL值视为0
SELECT [Cole_Crops],
PERCENT_RANK() OVER (PARTITION BY HUC02
ORDER BY CASE WHEN [Cole_Crops] IS NULL THEN 0 ELSE [Cole_Crops] END) AS Cole_Crops_PCT_RANK],
[Row_Crops],
PERCENT_RANK() OVER (PARTITION BY HUC02
ORDER BY CASE WHEN [Row_Crops] IS NULL THEN 0 ELSE [Row_Crops] END) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09
答案 2 :(得分:0)
您可以尝试在PARTITION BY子句中添加条件:
SELECT [Cole_Crops],
PERCENT_RANK() OVER (PARTITION BY [Cole_Crops] is not null, HUC02
ORDER BY [Cole_Crops]) AS Cole_Crops_PCT_RANK],
[Row_Crops],
PERCENT_RANK() OVER (PARTITION BY [Row_Crops] is not null, HUC02
ORDER BY [Row_Crops]) AS Row_Crops_PCT_RANK]
FROM V012_CDLMAX_09
答案 3 :(得分:0)
对韦斯的回答稍作修改。应该是:
CASE
WHEN COLUMN_1 IS NULL THEN NULL
ELSE PERCENT_RANK() OVER
(PARTITION BY
HUC02
END
ORDER BY COLUMN_1)
END AS RANK_COLUMN_1