簡體   English   中英

獲取負數最大的行,如果沒有負數,則獲取負數最小的行

[英]Get row with largest negative number, or row with smallest number if there are no negative numbers

我正在嘗試編寫執行以下操作的 Snowflake SQL 語句:

  • 如果 column_A 中有負數,則返回 column_A 中負數最大的行
  • 如果 column_A 中沒有負數,則返回 column_A 中數字最小的行

例如,如果我的表是:

列_A 列_B
-20 1
-5 2
1 3
15 4

結果應該是:-5, 2

如果我的表是:

列_A 列_B
1 3
15 4
20 5

結果應該是:1, 3

要創建示例表:

with example_table as (
    select
            $1::NUMBER as column_A
          , $2::NUMBER as column_B
    from
        (values
                 (-20, 1) 
               , (-5, 2)
               , (1, 3) 
               , (15, 4) 
        )
)

select * from example_table

就像是:

order by
    case when column_a < 0 then 1 else 2 end,
    abs(column_a)
offset 0 rows
fetch first 1 row only

基本上你在兩個假列上order by

  • 第一個將包含 1 用於所有負值,否則為 2,因此這會將所有負值放在首位(如果有)
  • 第二個將包含絕對值(例如 -5 變為 5,而 5 仍為 5)

可以使用SIGNABS來實現:

SELECT * 
FROM example_table
ORDER BY SIGN(COLUMN_A), ABS(COLUMN_A) LIMIT 1;

符號返回 -1 表示負數,0 表示零,1 表示正數。 ABS 返回按升序排序的絕對值。 LIMIT 1 將結果集限制為單行。

輸出:

在此處輸入圖像描述

在 SQL 中,我會寫:

SELECT (
    IFF (
        (SELECT COUNT(*) FROM myTable WHERE column_A < 0) > 0,
        SELECT * FROM myTable WHERE column_A = MAX(column_A),
        SELECT * FROM myTable WHERE column_A = MIN(column_A)
    ) );

這是 IFF 的文檔: https ://docs.snowflake.com/en/sql-reference/functions/iff.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM