📜  power query case when - SQL (1)

📅  最后修改于: 2023-12-03 15:33:46.354000             🧑  作者: Mango

Power Query Case When - SQL

Power Query is a powerful tool that allows you to perform data transformation tasks in a simple and easy-to-use interface. One of its capabilities is the ability to perform "case when" operations, which are similar to "if-then" statements in SQL.

Syntax

The basic syntax for a case when statement in Power Query is as follows:

= Table.AddColumn(Source, "Custom Column", each 
    if [column] = x then y
    else if [column] = z then w
    else v)

Here, Source is the name of the table or query that you want to modify, "Custom Column" is the name of the new column that you want to create, and [column] refers to the column in the source data that you want to evaluate.

The if-then-else structure allows you to define different actions for different conditions. If the condition in the first if statement is true, the corresponding value (in this case, y) is returned. If not, the next else if statement is evaluated, and so on. If none of the conditions are true, the else value (v) is returned.

Example

Let's say you have a table of sales data, with columns for region, product, and sales amount. You want to create a new column that assigns a category to each product based on its sales amount:

Region | Product | SalesAmount
-------|---------|------------
North  | A       | 100
North  | B       | 200
South  | A       | 150
South  | B       | 50

You can use a case when statement to accomplish this:

= Table.AddColumn(Source, "Category", each 
    if [SalesAmount] > 100 then "High"
    else "Low")

This will create a new column called "Category" that assigns a value of "High" if the sales amount is greater than 100, and "Low" otherwise:

Region | Product | SalesAmount | Category
-------|---------|------------|---------
North  | A       | 100        | Low
North  | B       | 200        | High
South  | A       | 150        | High
South  | B       | 50         | Low
Conclusion

Power Query's case when functionality is a powerful tool for performing complex data transformations. By allowing you to define different actions for different conditions, it can help you eliminate the need for complex SQL statements and simplify your data transformation tasks.