0% found this document useful (0 votes)
190 views15 pages

Power Query Tutorial

The document discusses Power Query if, if or, and if and statements. It provides examples of using each type of statement to add conditional columns to sample data tables. Power Query if statements are similar to Excel if statements but use lowercase if and then/else keywords. If or and if and statements can be created using the Add Custom Column dialog box by writing the formula. Nested if statements allow for multiple conditional checks.

Uploaded by

eramgo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
190 views15 pages

Power Query Tutorial

The document discusses Power Query if, if or, and if and statements. It provides examples of using each type of statement to add conditional columns to sample data tables. Power Query if statements are similar to Excel if statements but use lowercase if and then/else keywords. If or and if and statements can be created using the Add Custom Column dialog box by writing the formula. Nested if statements allow for multiple conditional checks.

Uploaded by

eramgo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Power Query Tutorial ESPAOL

Power Query if statements are a bit different to writing IF formulas in Excel, but once
you get the hang of them theyre pretty easy. In fact, the Power Query versions of IF
OR, and IF AND are even easier than the Excel equivalents.

Note: this tutorial assumes you already know how to write Excel IF, IF(OR and IF(AND
formulas. If you dont then here are the links to tutorials on IF formulas and IF(OR and
IF(AND formulas. It also assumes youre familiar with loading data into Power Query
and adding Custom Columns. If not then you can learn Power Query here or here.

Ok, lets look at an example; below we have some Orders data in Power Query.

We want to add a Delivery Status column to indicate whether the order has been
delivered.

The logic in English is, if the delivery date column is not blank, then the order has
been Completed.

Download the Excel File


1
Download the Excel Workbook. Note: This is a .xlsx file please ensure your browser
doesn't change the file extension on download.

Power Query if Statements


On the Add Column tab of the ribbon click Conditional Column. The dialog box
opens (see below) with an easy point and click menu to help you build the if
statement (note: null in Power Query means blank or empty):

Notice how you can read the if line in the dialog box and it actually makes sense in
English?

2
Digression: Maybe one day Excel formulas will catch up and well be blessed with a
similar dialog box.

And were back; after clicking OK we now have a new column for the Delivery Status:

And if you inspect the M code in the Advanced Editor you can see the formula below
has been written for you:

So, you can see that a regular Power Query if statement is dead easy to create with
the Conditional Column GUI.

Unfortunately you cant use the Conditional Column for every if scenario. Sometimes
youll have to use the Add Custom Column dialog box (see next example), and write
them yourself. In which case you should be aware of the key differences to the Excel
IF Statement, namely:

The if in Power Query is lower case


Instead of commas separating the value_if_true and value_if_false arguments
we have the words then and else (in lower case).
null means blank in Power Query
Power Query formulas are case sensitive

3
Power Query if or Statements
Did you notice that the example above doesnt allow for customers who come into the
store and collect their own orders? These are the In Store Pickup order types.

So what we actually need here is an IF OR statement.

The logic in English is: if the delivery date column is not blank OR the Order Type is
In Store Pickup, then the order has been Completed.

Unfortunately there isnt a nice GUI to help us write the if or statement so in this case
we use the Add Column tab > Add Custom Column button:

The dialog box opens and you have to give your column a name and then type your
formula into the Custom column formula: field:

4
Lets look at the formula more closely:

if [Delivery Date] <> null or [Order Type] = "In Store


Pickup" then "Completed" else null

In English the above formula reads:

If the Delivery Date is not blank or the Order Type is In store Pickup then return
Completedotherwise leave the cell blank

Each logical test is separated by or. Nice and easy, eh!

Power Query if and Statements


Power Query if and statements are equally easy. Lets look at an example using
some employee salary data shown below:

5
We want to add a column to calculate bonuses for the Executive level employees.

The logic in English is: if the Level is Executive AND the Target Met is Yes, then
calculate the bonus as Salary x 5%, otherwise zero bonus.

As with the if or statement, we have to use the Add Column > Add Custom Column
dialog box to write this formula:

if [Level] = "Executive" and [Target Met] = "Yes" then [Salary]


* .05 else 0

And you can see the results in the Bonus column below:

6
Holdup, what about bonuses for the Managers? Actually, the managers get 10%
bonus if they meet their targets.

We can accommodate two levels of bonus using a nested if statement.

Power Query Nested if Statements


Using the same sample data our logic in English reads: if the Level is Executive
AND the Target Met is Yes, then calculate the bonus as Salary x 5%, otherwise if the
Level is Manager AND the Target Met is Yes, then calculate the bonus as Salary x
10%, otherwise zero bonus.

And the formula is:

if [Level] = "Executive" and [Target Met] = "Yes" then


[Salary]*.05 else

if [Level] = "Manager" and [Target Met] = "Yes" then [Salary]*.10 else 0

The key is to put the next if statement after the first else. Ive wrapped the formula
onto two lines so its easier to see the nesting. You can continue nesting ifs after each
else.

More Power Query


If you've got 4 hours to spare on Nov 16 & 17 then I highly recommend you check
out this Power Query course by fellow MVP's Ken Puls and Miguel Escobar. Sign up
before Nov 11 and use coupon LAST2016 to get 15% off.

Or if you prefer to learn over a longer time period when it suits you please check out
my Power Query course.

And click here for more Power Query tutorials on our blog.

7
CONSULTAS CON POWER QUERY

Potencia para realizar consultas si las declaraciones son un poco diferentes a la


escritura si las frmulas en Excel, pero una vez que el cuelgue de ellos son bastante
fcil. De hecho, las versiones de potencia de consulta de SI O, y S Y son incluso ms
fcil que los equivalentes de Excel.

Nota: este tutorial asume que ya sabe cmo escribir Excel SI, SI (O y Si (y frmulas Si
no lo hace, entonces aqu estn los enlaces a tutoriales sobre. SI frmulas y SI (O y Si
(y frmulas Tambin. se supone que est familiarizado con la carga de datos en la
energa de consultas y la adicin de columnas personalizadas. Si no, entonces usted
puede aprender de alimentacin de consulta aqu o aqu.

Ok, vamos a ver un ejemplo; a continuacin tenemos algunos datos pedidos en la


energa de consulta.

Queremos agregar una columna "Estado de entrega" para indicar si el pedido ha sido
entregado.

8
La lgica en Ingls es , si la columna de la fecha de entrega no est en blanco,
entonces el orden se ha completado.

Descargar el archivo de Excel

Descargar el libro de Excel . Nota: Este es un archivo .xlsx asegrese de que su


navegador no cambiar la extensin del archivo de descarga.

Consulta poder si Declaraciones


Por Aadir columna pestaa de la cinta, haga clic en la columna condicional. Se
abre el cuadro de dilogo (vase ms adelante) con un punto de fcil y haga clic en el
men para ayudarle a construir la sentencia "if" (nota: 'nulo' en el poder de consulta
significa blanco o vaco) :

9
Observe cmo se puede leer la lnea "si" en el cuadro de dilogo y que en realidad
tiene sentido en Ingls?

Digresin: Tal vez un da las frmulas de Excel se pondr al da y vamos a estar


dotado de una caja de dilogo similar.

Y estamos de vuelta; despus de hacer clic en "Aceptar" ahora tenemos una nueva
columna para el Estado de Entrega:

Y si usted examina el cdigo M en el Editor avanzado se puede ver la siguiente


frmula ha sido escrito para usted:

Por lo tanto, se puede ver que una consulta de alimentacin regular si la declaracin
est muerto fcil de crear con la GUI Columna condicional.

Lamentablemente no se puede utilizar la columna condicional para cada escenario


"si". A veces, usted tiene que utilizar el cuadro de dilogo Aadir columna
personalizada (vase el siguiente ejemplo), y los escribe usted mismo. En cuyo caso,

10
usted debe ser consciente de las diferencias clave a la Declaracin de Excel SI, a
saber:

El " si" en el Poder consulta es minscula


En vez de comas que separan los argumentos valor_si_verdadero y
Valor_si_falso tenemos las palabras a continuacin, y dems (en
minsculas).
nula significa blanco en consultas de energa
frmulas de consulta de potencia entre maysculas y minsculas

Consulta poder si o declaraciones


Se dieron cuenta que el ejemplo anterior no permite a los clientes que entran en la
tienda y recoger sus propias rdenes? Estos son los '' En Recoger en tienda tipos de
rdenes.

As que lo que realmente se necesita aqu es una instruccin IF O.

La lgica en Ingls es: si la columna de la fecha de entrega no es blanco o el tipo de


orden es "En Recoger en tienda ', entonces el orden se ha completado.

Desafortunadamente no hay una interfaz grfica agradable para ayudarnos a escribir


el "si o" declaracin por lo que en este caso se utiliza la pestaa Agregar Columna>
Agregar columna personalizada botn:

11
El cuadro de dilogo se abrir y le tiene que dar su columna un nombre y despus
escriba su frmula en la "frmula de columna personalizada: 'campo:

Veamos ms de cerca la frmula:

si [Fecha de entrega] <> nula o [Tipo de Orden] = "En Recoger


en tienda" y luego "Completado" nula dems

En Ingls la frmula anterior se lee:

12
Si la fecha de entrega no est en blanco o el tipo de orden es "En la tienda de
recogida ' y luego volver' Completado ' lo contrario, deje la celda en blanco

Cada prueba lgica es separado por "o". Agradable y fcil, eh!

Consulta poder si y Declaraciones


Potencia para realizar consultas 'si y' declaraciones son igualmente fcil. Veamos un
ejemplo con algunos datos de los salarios de los empleados que se muestran a
continuacin:

Queremos aadir una columna para el clculo de las primas para los empleados de
nivel ejecutivo.

La lgica en Ingls es : Si el nivel es ejecutivo y el Alcanzamos el objetivo es S,


entonces calcular el bono como el salario x 5%, de lo contrario bono cero.

Al igual que con el "si o" declaracin, tenemos que utilizar la opcin Agregar
Columna> cuadro de dilogo Columna personalizada Aadir a escribir esta frmula:

13
si [nivel] = "Ejecutivo" y [Objetivo alcanzado] = "S", entonces
[salario] * 0,05 dems 0

Y se puede ver los resultados en la columna de la bonificacin a continuacin:

Atraco, qu pasa con los bonos para los Administradores? En realidad, los gerentes
obtienen un 10% de bonificacin si cumplen sus objetivos.

Podemos acomodar a dos niveles de bonificacin utilizando una sentencia if anidada.

Consulta poder if anidadas


Utilizando los mismos datos de la muestra nuestra lgica en Ingls lee : Si el nivel
es ejecutivo y el Alcanzamos el objetivo es S, entonces calcular el bono como el
salario x 5%, de lo contrario, si el nivel es gerente y el Alcanzamos el objetivo es S,
entonces el clculo de la bonificacin como el salario x 10%, de lo contrario bono
cero.

Y la frmula es:

si [nivel] = "Ejecutivo" y [Objetivo alcanzado] = "S", entonces


[salario] *. 05 otra cosa

si [nivel] = "Administrador" y [Met destino] = "S", entonces [salario] *. 10 otra cosa 0

La clave es poner la siguiente sentencia "if" despus de la primera 'otra cosa'. Me he


envuelto la frmula en dos lneas por lo que es ms fcil ver la anidacin. Puede
continuar anidando "si" despus de cada 'cosa'.

14
Ms de consultas de energa
Si tienes 4 horas libres el 16 de noviembre y 17 entonces le recomendamos que
consulte a cabo este curso de alimentacin de consulta por su compaero de MVP
Ken Puls y Miguel Escobar. Inscribirse antes del 11 de noviembre y utilizar LAST2016
cupn para obtener 15% de descuento .

O si lo prefiere aprender en un perodo de tiempo ms largo cuando conviene a usted


por favor echa un vistazo a mi curso de alimentacin de consultas . Y haga clic
aqu para ms tutoriales de alimentacin de consulta en nuestro blog.

15

You might also like