新增條件式數據行

使用 Power Query,您可以建立新的數據行,其值是以套用至數據表中其他數據行的一或多個條件為基礎。

[條件數據行] 命令位於 [一般] 群組中的 [新增數據行] 索引標籤上。

Screenshot of the Power Query ribbon with the Add column tab open and the Conditional column option emphasized.

新增條件式數據行

在此範例中,您會使用下圖所示的數據表。

Screenshot of the sample table to use when adding a conditional column.

在此表格中,您有一個字段 可提供 CustomerGroup。 您也有適用於第 1 層價格、第 2 層價格第 3 層價格欄位的客戶不同的價格。 在此範例中,您的目標是根據 CustomerGroup 字段中找到的值,建立名稱為 Final Price 的新數據行。 如果 CustomerGroup 欄位中的值等於 1,則您想要使用第 1 層價格字段中的值;否則,您會使用第 3 層價格的值

若要新增此條件數據行,請選取 [ 條件式數據行]。 在 [ 新增條件式數據行 ] 對話框中,定義下列區段:

  • 新的資料行名稱:定義新資料行的名稱。 在此範例中,請使用名稱 Final Price
  • 條件子句:定義條件子句。 您可以選取 [新增子句] 來新增更多子句。 每個條件子句都會在對話框中顯示的順序上測試,從上到下。 每個子句都有四個部分:
    • 數據行名稱:在下拉式清單中,選取要用於條件測試的數據行。 在此範例中,選取 [CustomerGroup]。
    • 運算子:選取條件式測試的測試或運算符類型。 在此範例中 ,CustomerGroup 數據行中的值必須等於 1,因此請選取 [等於]。
    • :輸入值,或選取要用於條件測試的數據行。 在此範例中,輸入 1
    • 輸出:如果測試為正數,則在此處輸入的值,或選取的數據行是輸出。 在此範例中 ,如果 CustomerGroup 值等於 1,您的 輸出 值應該是第 1 層價格 數據行中的值。
  • Final Else 子句:如果上述子句都沒有產生正面測試,此作業的輸出就是這裡定義的子句,做為手動輸入的值或數據行的值。 在此情況下,輸出是第 3 層價格數據行的值

Screenshot of the Add conditional column dialog with all of the example values filled in.

該作業的結果會提供新的 Final Price 數據行,其中包含第 1 層價格 和第 3 層價格數據行的值。

Screenshot of the table with the Final Price column containing the Any data type produced by the example conditional clauses.

注意

新的條件式數據行未定義資料類型。 您可以依照Power Query 中資料類型中所述的步驟,新增步驟來定義這個新建立資料行的數據類型。

新增及組織多個子句

在此範例中,讓我們變更您的目標。 您的新條件子句如下:

  • 如果 CustomerGroup 數據行的值等於 1,則 Output 是第 1 層 Price 數據行的值
  • 如果 CustomerGroup 數據行中的值等於 2,則 Output 是第 2 層 Price 數據行的值
  • 如果先前的測試都不是正面的,則 Output 是第 3 層價格數據行的值

Screenshot of Add conditional column with two different conditional clauses defined for the values of the Final Price column.

注意

在每個子句結尾,您可以選取省略號按鈕 (...) 來刪除、上移或下移子句。

該作業的結果會為您提供最終價格數據行,其中包含第 1 層價格、第 2 層價格和第 3 層價格數據行的價格。

Screenshot of the table with the Final Price that contains the Any data type produced by the multiple conditional clauses.