使用row_number SQL Server时跳过null或0值

问题描述

我正在尝试从数据中获取row_number,但是我想跳过null或0值

DECLARE @ProcessId INT = 6013006
DECLARE @CommHeaderId int

SELECT  @CommHeaderId = a.id
FROM    EprocUltimate.dbo.commercial_header a 
WHERE   a.process_id = @ProcessId

SELECT  b.rank_quotation,c.rank_nego,CASE ISNULL(a.quotation_usd,0) WHEN 0 THEN a.quotation_idr ELSE a.quotation_usd END As  Quotation,CASE ISNULL(a.nego_usd,0) WHEN 0 THEN a.nego_idr ELSE a.nego_usd END As Nego
FROM    EprocUltimate.dbo.commercial_vendor a
        INNER JOIN 
        (
            SELECT  a.id,ROW_NUMBER() OVER(ORDER BY CASE quotation_usd WHEN 0 THEN quotation_idr ELSE quotation_usd END ASC) AS rank_quotation
            FROM    EprocUltimate.dbo.commercial_vendor a
            WHERE   a.commercial_header_id = @CommHeaderId AND a.commercial_admin_bid_evaluation_result = 'Pass'
        ) b ON a.id = b.id
        INNER JOIN
        (
            SELECT  a.id,ROW_NUMBER() OVER(ORDER BY CASE ISNULL(nego_usd,0) WHEN 0 THEN nego_idr ELSE nego_usd END ASC) AS rank_nego          
            FROM    EprocUltimate.dbo.commercial_vendor a
            WHERE   a.commercial_header_id = @CommHeaderId AND a.commercial_admin_bid_evaluation_result = 'Pass'
        ) c ON a.id = c.id
WHERE   a.commercial_header_id = @CommHeaderId AND a.commercial_admin_bid_evaluation_result = 'Pass'
ORDER BY b.rank_quotation

结果在这里

rank_quotation rank_nego,value1,value2
1                  3      775460000.00  770000000.00
2                  1      781036525.00  NULL
3                  2      786250000.00  NULL

从此查询中,我想要得到的是具有优先值的row_numbering rank_nego

所以我想要达到的结果是

rank_quotation rank_nego,value2
1                  1      775460000.00  770000000.00
2                  2      781036525.00  NULL
3                  3      786250000.00  NULL

解决方法

您可以使用一些变通方法来使NULL值作为带有ROW_NUMBER() OVER (ORDER BY ...) as rank_nego的子查询中的最后一条记录

(
    SELECT  a.id,ROW_NUMBER() OVER(ORDER BY 
       -- This statement will first sort records having nego_usd and nego_idr as NULL/0 at the end of the list 
       CASE WHEN ISNULL(nego_usd,0) = 0 AND ISNULL(nego_idr,0) = 0 THEN 1 ELSE 0 END ASC,-- and then sort with the real values
       CASE ISNULL(nego_usd,0) WHEN 0 THEN nego_idr ELSE nego_usd END ASC
    ) AS rank_nego
    FROM    EprocUltimate.dbo.commercial_vendor a
    WHERE   a.commercial_header_id = @CommHeaderId AND a.commercial_admin_bid_evaluation_result = 'Pass'
) c ON a.id = c.id    

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...