

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# Ifelse
<a name="ifelse-function"></a>

`ifelse` 會評估一組 *if* 和 *then* 表達式對，並傳回第一個評估結果為 true 的 *if* 引數的 *then* 引數值。如果 *if* 引數評估為 true，則會傳回 *else* 引數的值。

## 語法
<a name="ifelse-function-syntax"></a>

```
ifelse(if-expression-1, then-expression-1 [, if-expression-n, then-expression-n ...], else-expression)
```

## 引數
<a name="ifelse-function-arguments"></a>

`ifelse` 需要一或多個 *if* 和 *then* 表達式配對，加上 *else* 引數的正好一個表達式。

 *if-expression*   
要評估為 true 或否的表達式。它可以是 **address1** 之類的欄位名稱、**'Unknown'** 之類的常值，或 `toString(salesAmount)` 之類的函數。例如，`isNotNull(FieldName)`。  
如果您在 `if` 引數中使用多個 AND 和 OR 運算子，請將陳述式含括在括號中，以識別處理順序。例如，下列 `if` 引數會傳回月份 1、2、或 5 且年份為 2000 年的記錄。  

```
ifelse((month = 5 OR month < 3) AND year = 2000, 'yes', 'no')
```
下一個 `if` 引數會使用相同的運算子，但傳回月份為 5 和任何年份，或月份為 1 或 2 且年份為 2000 年的記錄。  

```
ifelse(month = 5 OR (month < 3 AND year = 2000), 'yes', 'no')
```

 *then-expression*   
如果其 *if* 引數評估為 true，要傳回的表達式。它可以是 **address1** 之類的欄位名稱、**'Unknown'** 之類的常值，或對另一個函數的呼叫。運算式必須與其他 `then` 引數和 `else` 引數擁有相同的資料類型。

 *else-expression*   
如果沒有任何 *if* 引數評估為 true，要傳回的表達式。它可以是 **address1** 之類的欄位名稱、**'Unknown'** 之類的常值，或 `toString(salesAmount)` 之類的函數。運算式必須與所有 `then` 引數擁有相同的資料類型。

## 傳回類型
<a name="ifelse-function-return-type"></a>

`ifelse` 會傳回與 *then-expression* 中的值具有相同資料類型的值。從 *then* 和 *else* 表達式傳回的所有資料必須具有相同的資料類型或轉換為相同的資料類型。

## 範例
<a name="ifelse-function-example"></a>

以下範例為欄位 `country` 產生別名資料欄。

```
ifelse(country = "United States", "US", country = "China", "CN", country = "India", "IN", "Others") 
```

對於此類根據常值清單評估欄位中每個值，並傳回與第一個相符值相對應的結果的使用案例，建議使用函數 switch 來簡化工作。可以使用 [https://docs.aws.amazon.com/quicksight/latest/user/switch-function.html](https://docs.aws.amazon.com/quicksight/latest/user/switch-function.html) 將前面的範例重寫為以下陳述式：

```
switch(country,"United States","US","China","CN","India","IN","Others")
```

以下範例將每位客戶的銷售額分類為人類可讀的等級。

```
ifelse(salesPerCustomer < 1000, “VERY_LOW”, salesPerCustomer < 10000, “LOW”, salesPerCustomer < 100000, “MEDIUM”, “HIGH”)
```

以下範例使用 AND、OR 和 NOT 來比較多個表達式，使用條件運算子來標記特殊促銷活動中，不在華盛頓或奧勒岡、提出了 10 個以上訂單的前幾大客戶。如果沒有傳回任何值，則會使用值 `'n/a'`。

```
ifelse(( (NOT (State = 'WA' OR State =  'OR')) AND Orders > 10),  'Special Promotion XYZ',  'n/a')
```

以下範例僅使用 OR 產生一個新資料欄，其中包含與每個 `country` 對應的大洲名稱。

```
ifelse(country = "United States" OR country = "Canada", "North America", country = "China" OR country = "India" OR country = "Japan", "Asia", "Others")
```

前面的範例可以簡化稱如下範例。以下範例使用 `ifelse` 和 [https://docs.aws.amazon.com/quicksight/latest/user/in-function.html](https://docs.aws.amazon.com/quicksight/latest/user/in-function.html) 針對測試值位於常值清單中的任何列在新資料欄中建立一個值。您也可以將 `ifelse` 與 [https://docs.aws.amazon.com/quicksight/latest/user/notIn-function.html](https://docs.aws.amazon.com/quicksight/latest/user/notIn-function.html) 搭配使用。

```
ifelse(in(country,["United States", "Canada"]), "North America", in(country,["China","Japan","India"]),"Asia","Others")
```

作者可以將常值清單儲存在多值參數中，並在 [https://docs.aws.amazon.com/quicksight/latest/user/in-function.html](https://docs.aws.amazon.com/quicksight/latest/user/in-function.html) 或 [https://docs.aws.amazon.com/quicksight/latest/user/notIn-function.html](https://docs.aws.amazon.com/quicksight/latest/user/notIn-function.html) 函數中使用。以下範例與前面的範例等效，只是這裡的常值清單儲存在兩個多值參數中。

```
ifelse(in(country,${NorthAmericaCountryParam}), "North America", in(country,${AsiaCountryParam}),"Asia", "Others") 
```

以下範例會根據銷售總計，將群組指派給銷售記錄。每個 `if-then` 片語的結構模仿 *between* (該關鍵字目前在計算欄位表達式中不起作用) 的行為。例如，比較 `salesTotal >= 0 AND salesTotal < 500` 的結果傳回與 SQL 比較 `salesTotal between 0 and 499` 相同的值。

```
ifelse(salesTotal >= 0 AND salesTotal < 500, 'Group 1', salesTotal >= 500 AND salesTotal < 1000, 'Group 2', 'Group 3')
```

以下範例透過使用 `coalesce` 傳回第一個非 NULL 值來測試 NULL 值。您可以為日期欄位使用可讀的描述，從而無需記住 NULL 的含義。如果中斷連線日期為 NULL，則此範例會傳回暫停日期，除非兩者皆為 NULL。然後 `coalesce(DiscoDate, SuspendDate, '12/31/2491')` 會回傳 `'12/31/2491'`。傳回值必須與其他資料類型相符。這個日期看似一個不尋常的值，但 25 世紀的某個日期作為「結束時間」 (定義為資料市集中的最晚日期) 是合理的。

```
ifelse (  (coalesce(DiscoDate, SuspendDate, '12/31/2491') = '12/31/2491'),  'Active subscriber', 'Inactive subscriber')
```

下面以更易讀的格式顯示了一個更複雜的範例，目的在於表明您不需要將所有程式碼壓縮成一長行。此範例提供了對調查結果值的多重比較。它處理該欄位的潛在 NULL 值，並對兩個可接受的範圍進行分類。它還標記了一個需要更多測試的範圍，以及另一個無效 (超出範圍) 的範圍。對於所有剩餘值，它會套用 `else` 條件，並將相應列標記為需要在列上的日期三年後重新測試。

```
ifelse
( 
    isNull({SurveyResult}), 'Untested',  
    {SurveyResult}=1, 'Range 1', 
    {SurveyResult}=2, 'Range 2', 
    {SurveyResult}=3, 'Need more testing',
    {SurveyResult}=99, 'Out of Range',
    concat  
    (
        'Retest by ', 
        toString    
        (
           addDateTime(3, "YYYY", {Date}) 
        )
    )
)
```

以下範例將「手動」建立的地區名稱指派給一個州名群組。它還使用空白和包含在 `/* */` 中的註解，以便讓維護程式碼更輕鬆。

```
ifelse 
(    /* NE REGION*/
     locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) > 0,
    'Northeast',

     /* SE REGION*/
     locate('Georgia, Alabama, South Carolina, Louisiana',{State}) > 0,
    'Southeast',

    'Other Region'
)
```

地區標記的邏輯分解如下：

1. 我們列出每個地區相應的州，將每個清單括在引號中以使每個清單成為一個字串，如下所示：
   + `'New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire'`
   + `'Georgia, Alabama, South Carolina, Louisiana'`
   + 您可以新增更多集合，或根據需要使用國家/地區、城市、省份或 What3Words。

1. 我們使用 `locate` 函數詢問是否在清單中找到了 `State` (每列) 的值，如果在清單中找到了相應州，則傳回非零值，如下所示。

   ```
   locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) 
   
   and
   
   locate('Georgia, Alabama, South Carolina, Louisiana',{State})
   ```

1. `locate` 函數傳回一個數字，而不是 `TRUE` 或 `FALSE`，但 `ifelse` 需要 `TRUE`/`FALSE` 布林值。為了解決這個問題，我們可以將 `locate` 的結果與某個數字進行比較。如果相應州在清單中，則傳回值大於零。

   1. 詢問相應州是否存在。

      ```
      locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) > 0
      ```

   1. 如果存在於相應地區，則將其標記為特定地區，在本例中為 Northeast 地區。

      ```
      /*The if expression:*/     locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) > 0,
      /*The then expression:*/   'Northeast',
      ```

1. 由於有些州不在清單中，而且 `ifelse` 需要單一 `else` 表達式，因此我們提供 `'Other Region'` 作為剩餘州的標籤。

   ```
   /*The if expression:*/     locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) > 0,
   /*The then expression:*/   'Northeast',
   /*The else expression:*/   'Other Region'
   ```

1. 我們將所有內容包裝在 `ifelse( )` 函數中以取得最終版本。以下範例省略了原始範例中屬於 Southeast 地區的州。您可以使用它們取代 *`<insert more regions here>`* 標籤將它們加回來。

   如果您想新增更多地區，您可以建立這兩行的更多複本，並變更州清單以滿足您的需求。您可以將地區名稱變更為所需名稱，並將欄位名稱從 `State` 變更為您需要的任何名稱。

   ```
   ifelse 
   (
   /*The if expression:*/     locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) > 0,
   /*The then expression:*/   'Northeast',
   
   /*<insert more regions here>*/
   
   /*The else expression:*/   'Other Region'
   )
   ```
**注意**  
還有其他方法可以對上述 if 表達式進行初始比較。例如，假設您提出問題「此清單中未缺少哪些州？」，而不是「哪些州在清單上？」。如果是這樣，那麼編碼可能會不同。您可以將 locate 陳述式與零進行比較，以尋找清單中缺少的值，然後使用 NOT 運算子將它們分類為「未缺失」，如下所示。  

   ```
   /*The if expression:*/      NOT (locate('New York, New Jersey, Connecticut, Vermont, Maine, Rhode Island, New Hampshire',{State}) = 0),
   ```
兩個版本均正確。不論選擇何版本，應該讓編碼易於您和您的團隊理解，從而讓維護程式碼更輕鬆。如果所有選項看起來等效，則建議選擇最簡單的選項。