使用 row_number sql 服务器时跳过 null 或 0 值

skip null or 0 value while using row_number sql server

我正在尝试从数据中获取 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_number首先 rank_nego 具有值

所以我想要达到的结果是

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

您可以使用一些变通方法,使用 ROW_NUMBER() OVER (ORDER BY ...) as rank_nego

将 NULL 值作为子查询中的最后记录
(
    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