Tag: Beginner Skill Level

  • Load Multiple Excel (xls or xlsx) Files

    Load Multiple Excel (xls or xlsx) Files

    Previously we’ve done a tutorial on loading multiple text files within one query.  This is nice, however we will also need to import multiple Excel files.  First, to understand the procedure of querying multiple excel files you have to understand the basics between the CSV (comma separated values) file and an excel (.xls or .xlsx) files.  In a CSV file you have only one data set.  The beginning of the file starts with values and separates each file with a “,”  a carriage return starts a new row of data.  This is an easy and efficient way to store millions of rows of data.  By contrast the excel file is way more complicated.  Excel files can have multiple sheets of tables of data.  Think of this as a stack of CSV type files.  For example if you have an excel workbook with three sheets of data, Sheet 1, Sheet 2, Sheet 3.  You can think of those three sheets as grid of data, similar to the CSV file.  The multiple sheet aspects of an excel file makes the data ingestion into PowerBI a little bit more complicated.  To add to the complication, when you loading data from either multiple sheets, or selecting a specific out of many sheets of data.  For illustration purposes imagine working with two excel files with three sheets each, 2 x 3 = 6, a total of 6 sheets of data, or what I will call “pages” of data.  This is why it is more complex to load excel files than CSV files.

    Note: If you want to learn how to load multiple CSV files visit this tutorial.

    Not only do you have to figure out what data you want to ingest on the page you must all tell PowerBI which sheets do you want to look at, and from which excel file.  If that was to many words think of loading the following data sample:

    Workbook 1 – Year 2000 Olympic Medals

    • Sheet 1
      • Olympic Medals Table
        • Rank
        • Country
        • Gold
        • Silver
        • Bronze
        • Total
    • Sheet 2
    • Sheet 3

    WorkBook 2 – Year 2004 Olympic Medals

    • Sheet 1
      • Olympic Medals Table
        • Rank
        • Country
        • Gold
        • Silver
        • Bronze
        • Total
    • Sheet 2
    • Sheet 3

    The data structure for both workbook 1 and 2 are similar but the names of the files are different and there can be multiple pages.

    To resolve this we will have to write a M language function that will load each file as a function.  This will be done in later in the tutorial.

    Here is the data source information for Olympic medals won by each country from 2000 to 2012, download here.  Inside the Medal Count zip file are four xlsx files, extract them to your desktop.  Move the files into a folder on your desktop labeled Medals.

     

    Medals Folder
    Medals Folder

    Now, open up PowerBI,  We will begin shaping our data to load all the excel files.  On the Home ribbon click on the Get Data button.  Select Folder on the right side and click Connect.

    Get Folder Data
    Get Folder Data

    Next select the folder path that you want acquire the files from, Click OK to continue.

    Load Folder Screen
    Load Folder Screen

    Next we are presented with the loaded files within our selected folder.  Click Edit at the bottom of the screen to proceed.  The Query Editor window will now open.  Select the first two columns labeled Content, and Name.  With those two columns selected right click on the header and select Remove Other Columns. This will remove all the useless data associated with the files.

    Remove Other Columns
    Remove Other Columns

    Click the Add Column ribbon and press the Add Custom Column on the left side of the ribbon.

    Add Custom Column
    Add Custom Column

    Name the new column ExcelFileLoad and enter the following equation.

    Excel.Workbook Equation
    Excel.Workbook Equation

    Note: Once you type “Excel.Workbook(” you can click on the column labeled Content on the right side of the screen to have the name automatically added.  This is useful when you have many many columns to choose from or if there naming of those columns becomes complex.  This way you won’t type in the column name incorrectly.

    Click OK to proceed.  Notice we now have a new column called ExcelFileLoad.  Next click the Expand button (the one with the arrows) located at the right of our newly added column. Click OK to proceed.

    Expand Column Button
    Expand Column Button

    Now we have a new column labeled ExcelFileLoad.Data, which is the data contained in our excel files.  Now click in the Grey Area next to the word labeled Table.  This will open up the file and reveal the information present in the file.  Notice that we can see the headers and the data in our file.  Row 1 contains the headers of each column.  Rows after row 1 contains the medal data.

    View Data of File
    View Data of File

    Next select the columns labeled Name and ExcelFileLoad.Data and right click on the column header, then select Remove Other Columns

    Remove Other Columns Again
    Remove Other Columns Again

    On the Add Column ribbon click Add Custom Column again.  Name the column PromoteHeaders and enter the following formula. Click OK to proceed.

    Promote Headers Step
    Promote Headers Step

    Clicking again on the grey area in our newly created column reveals our tables with promoted headers.

    View of Data with Promoted Headers
    View of Data with Promoted Headers

    Next click the Expand Button, un-check the Use original column name as prefix and click the OK button to proceed.

    Expand Data
    Expand Data

    Remove the following columns, ExcelFileLoad.Data, Rank,  and Total, bu right selecting the columns and right clicking on the header and selecting Remove Columns.  Now we want to parse out the year name from the Name column.  To do this click on Name Column.  Then click the Transform ribbon and click the Extract button, then select First Characters from the drop down menu.

    Extract First Characters
    Extract First Characters

    In the Extract First Characters menu enter the number 4 and click OK to proceed.

    Extract First 4 Characters
    Extract First 4 Characters

    Change the following columns to whole numbers: Name, Gold, Silver, Bronze.  Do this on the Transform ribbon in the Data Type drop down.

    Change Data Types
    Change Data Types

    We are now ready to load all the data.  Rename the Query to Medals, click the Home ribbon and select Close & Apply.

    Name Query
    Name Query

    And there you have it.  We have successfully loaded four excel files into one query.

    Bonus: for added flare add the following measure.

    Total Medal Count = sum(Medals[Gold]) + sum(Medals[Silver]) + sum(Medals[Bronze])

    Now you can add the following Visualizations.

    Bar Chart Visual
    Bar Chart Visual
    Stacked Bar Chart
    Stacked Bar Chart
    Map Visual
    Map Visual
  • Measures – Intelligent Card Visual – Using DAX

    Measures – Intelligent Card Visual – Using DAX

    As I have been exploring PowerBI and building dashboards I have noticed that often the visuals can obscure your data.  As you click on different visuals there is a need to highlight different pieces of data.  Take for example the following dashboard:

    Sample Visual Example
    Sample Visual Example

    Notice the different car types in the bar chart.  As you click on each vehicle type, Diesel, Hatchback, etc.. you expect the data to change accordingly.  In some cases it is helpful to present a card visual to show the user what you selected and any relevant data points you want to highlight.  For example if I select the Diesel vehicle type I may want to know the average sales amount, total sales in dollars, or number of units sold.  This is where we can build specific measures that will intelligently highlight selected data within your PowerBI visual.

    Here is a sample of what we will be building today:

    lets begin with starting with some data.  In honor of your news feed being bombarded with Pokemon Go articles lets enter some data on Pokemon characters.

    We will enter our data manually.  For a full tutorial on manually entering in data visit here.

    Click the Enter Data button on the Home ribbon and enter the following information into the displayed table.

    Pokemon XP
    Pikachu 1200
    Weedle 650
    Pidgey 800
    Golbat 300

    Rename the table to Characters.  Once you are finished entering in the data it should look like the following:

    Create Table of Characters
    Create Table of Characters

    Click Load to continue.

    Start to examine your data by building a table visual.

    Table Visual
    Table Visual

    Next add a Bar chart.

    Bar Chart
    Bar Chart

    Note: I added the XP column twice.  Once to the Value attribute and to the Color Saturation.  This enhances the look of your visual by coloring the bars with a gradient.  The largest bar will have the darkest color, and the smallest bar will have the lightest color.

    Next, we will begin building some measures.  The first measure will be a total of all the experience points (XP) for each character. Click the New Measure button on the Home ribbon and enter the following DAX expression:

    Total XP = Sum(Characters[XP])

    Now, add a Card visual and add the new measure we created Total XP.

    Total XP Card Visual
    Total XP Card Visual

    This measure totals all the experience points for all the selected characters within the visual.  Since all characters are now selected the total XP for all characters is 2,950.

    The next, and final measure, will be the intelligent card.  For this measure we want to display the characters name when we select them in the bar chart.  Click the New Measure button on the Home ribbon and enter the following DAX expression:

    Character(s) = IF( DISTINCTCOUNT(Characters[Pokemon]) = 1 , FIRSTNONBLANK('Characters'[Pokemon],'Characters'[Pokemon]) , DISTINCTCOUNT('Characters'[Pokemon]) & " Selected")

    Update: As of Mid 2017 Microsoft introduced a new DAX expression called SELECTEDVALUE which greatly simplifies this equation.  Below is an example of how you would change the DAX equation to use SELECTEDVALUE.

    Selected = SELECTEDVALUE(  Characters[Pokemon],  DISTINCTCOUNT(  Characters[Pokemon]  )  &  " Selected" )

    Explanation of this measure:

    This measure first checks to see how many distinct items are in the column Pokemon of our dataset.  If there is only one selected character then we will display the FIRSTNONBLANK character, which will be the name of our selected character.  If there are more than one characters selected. The measure will count the number of characters selected and return a text string with the count and the word SelectedThus, showing us how many items have been selected.

    Add the measure titled Character(s) to a card visual.

    Add Character Card Visual
    Add Character Card Visual

    We can now see that there are 4 characters selected.  Clicking on Pikachu in the bar chart resolves with the character’s name being displayed and the XP of Pikachu being displayed in the Total XP card visual.

    Selecting Pikachu
    Selecting Pikachu

    You can select multiple items by holding down Ctrl and clicking multiple items in the bar chart.

    Selecting Pikachu and Pidgey

    Well, that is it.  I hope you enjoyed this Pokemon themed tutorial.  Thanks for visiting.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Loading Data From Folder

    Loading Data From Folder

    Let me setup a scenario for you.  You get a data file from an automated system, it has the same number of columns but the data changes for every new file.  Being the data savvy person that you are you’ve spent some time working in excel to make a template where you can copy your new data into and then automatically all your equations and graphs magically work.  You pat your self on the back and happily send out your fantastic report to everyone you know.  Then tomorrow when the data comes to you again you repeat the same process over again.  Still enamored by your awesome report, you send it out again knowing you have saved your self so much time not having to do the analysis or creation of your reports over and over again.  Now, fast forward 3 months.  That stupid report shows up again, and now you have to lug all that data from file to file and begrudgingly you sent out your report.  Thus, is the store of the analyst.  You love data, but you hate it as well.  Well in this tutorial I’ll show you how to remove some of the pain of that continual data loading process by loading new data from a folder.

    My previous post (found here) talks about loading data from a folder.  In this tutorial we will add some logic to this method that will look at a folder but only load the most recently added item from that folder.

    Data for this tutorial is located this link Monthly Data Zip File.  This data in the ZIP file is a monthly data sample from Feb 2016 to April of 2016.

    Download the zip file mentioned above and extract the Monthly Data folder down to your desktop.  Open up PowerBI Desktop and click on the Get Data button and select All on the left side.  Click on the item labeled Folder and click Connect to continue.

    Get Data from Folder
    Get Data from Folder

     

    Select the newly unzipped Monthly Data folder that should be on your desktop.  Click OK to continue. Upon opening that folder location you will be presented with the multiple files.  Click Edit to edit the query.

    Edit Query for Folder Load
    Edit Query for Folder Load

    Now you are in the Query Editor.  This is where the fancy query editing will work to our advantage.  We could load all the data into one large query.  However, depending on the size of your data sets or how you want to report your data this may not always be desirable.  Instead you may only want data from April, then May when the new data is sent next month.

    Thus, our first step to start pairing down the data will be to first filter the files in sequential order.  In this case because I have named the files with a Year-Month-Day format I can sort the files according to their names.

    Note:  When using PowerBI desktop it is a good practice to name the files  beginning with a YYYY-MM-DD file name.  This makes it really easy when sorting and ingesting information into PowerBI.  I have used other columns of information such as Date Accessed or Date Created before but have gotten inconsistent results as these dates can change depending on when a file was moved or copied from one place to another.

    Click the drop down next to Name and sort the files in Sort Descending.

    Name in Descending Sort
    Name in Sort Descending

    This places the files with the most recent file at the top of the list.

    File List in Descending Order
    File List in Descending Order

    Next click on the Keep Rows button on the Home ribbon, select Keep Top Rows.

    Keep Top Rows
    Keep Top Rows

    Enter the number when the popup appears.  Click OK to continue.

    Keep Top Rows Menu
    Keep Top Rows Menu

    Now you’ll notice you have only one file selected which is our latest file from April.  Click the Load File button found in the Content column.

    Load File Button
    Load File Button

    We have completed the activities in the Query Editor and can now load the data.  Click Close & Apply found on the Home ribbon.  All our April data has loaded.  by making a simple table we can now see all the data that was just loaded.

    Loaded Data from April
    Loaded Data from April

    Now we will remove some data from our desktop folder labeled monthly data.  Open the folder on the desktop labeled Monthly Data and delete the filed labeled 2016-04-01 April.  You should now have a folder labeled Monthly Data with only two files in it, one for Feb and one for March.

    Two Files Left
    Two Files Left

    Return back to Power BI Desktop and click the Refresh button on the Home ribbon.  Notice now how all our data has changed.  We are now looking at the March data because it is the most recent file in our folder based on the file name.

    March Data Load
    March Data Load

    To verify this we open the query editor (Click the Edit Queries on the Home ribbon).  Click Refresh Preview on the Home ribbon and finally select the Applied Step called Kept First Rows.  This will reveal the month of March as our data source.

    Month of March Loaded
    Month of March Loaded

    Now, every time you add a new file to our folder and refresh PowerBI the latest file (based on the naming convention we talked about earlier) will always be loaded.

    Note: This method works great when your data source is coming from an automated system.  The file format must always be the same for this to work reliability.  If the file naming convention changes, or the number of columns or location of those columns changes then the query will most likely fail.

    Good luck and thanks for following along.

  • Measures – Dynamic CAGR Calculation in DAX

    Measures – Dynamic CAGR Calculation in DAX

    This tutorial walks through calculating a dynamic Compound Annual Growth Rate (CAGR).  By dynamic we mean as you select different items on a bar chart for example the CAGR calculation will update to reveal the CAGR calculation only for the selected data.  See the example below:

    Lets start off by getting some data.  For this tutorial we will gather data from World Bank found here.  To make this process less about acquiring data and more about calculating the CAGR. Below is the Query Editor code you can copy and paste directly into the Advance Editor.

    let
     Source = Excel.Workbook(Web.Contents("https://powerbitips03.blob.core.windows.net/blobpowerbitips03/wp-content/uploads/2017/11/Worldbank-DataSet.xlsx"), null, true),
     EconomicData_Table = Source{[Item="EconomicData",Kind="Table"]}[Data],
     #"Changed Type" = Table.TransformColumnTypes(EconomicData_Table,{{"Country Name", type text}, {"Country Code", type text}, {"Indicator Name", type text}, {"Indicator Code", type text}, {"1960", type number}, {"1961", type number}, {"1962", type number}, {"1963", type number}, {"1964", type number}, {"1965", type number}, {"1966", type number}, {"1967", type number}, {"1968", type number}, {"1969", type number}, {"1970", type number}, {"1971", type number}, {"1972", type number}, {"1973", type number}, {"1974", type number}, {"1975", type number}, {"1976", type number}, {"1977", type number}, {"1978", type number}, {"1979", type number}, {"1980", type number}, {"1981", type number}, {"1982", type number}, {"1983", type number}, {"1984", type number}, {"1985", type number}, {"1986", type number}, {"1987", type number}, {"1988", type number}, {"1989", type number}, {"1990", type number}, {"1991", type number}, {"1992", type number}, {"1993", type number}, {"1994", type number}, {"1995", type number}, {"1996", type number}, {"1997", type number}, {"1998", type number}, {"1999", type number}, {"2000", type number}, {"2001", type number}, {"2002", type number}, {"2003", type number}, {"2004", type number}, {"2005", type number}, {"2006", type number}, {"2007", type number}, {"2008", type number}, {"2009", type number}, {"2010", type number}, {"2011", type number}, {"2012", type number}, {"2013", type number}, {"2014", type number}, {"2015", type number}, {"2016", type number}, {"2017", type any}}),
     #"Removed Other Columns" = Table.SelectColumns(#"Changed Type",{"Country Name", "2011", "2012", "2013", "2014", "2015", "2016"}),
     #"Filtered Rows" = Table.SelectRows(#"Removed Other Columns", each [2011] <> null and [2012] <> null and [2013] <> null and [2014] <> null and [2015] <> null and [2016] <> null),
     #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Filtered Rows", {"Country Name"}, "Attribute", "Value"),
     #"Renamed Columns" = Table.RenameColumns(#"Unpivoted Other Columns",{{"Country Name", "Country"}, {"Attribute", "Year"}, {"Value", "GDP"}})
    in
     #"Renamed Columns"

    Note: The tutorial on how to copy and paste the code into the Query Editor is located here.

    Paste the code above into the advance editor.  Click Done to load the query into the the Query Editor.  Rename the Query to World GDP and then on the home ribbon click Close & Apply.

    World GDP Query
    World GDP Query

    Loading the query loads the following columns into the fields bar on the right hand side of the screen.

    Fields Load from World GDP
    Fields Load from World GDP

    Next we will build a number of measure that will calculate the required variables to be used in our CAGR calculation.  For reference the CAGR calculation is as follows: (found from investopia.com)

    CAGR Calculation Image
    CAGR Calculation

    For each variable on the right of the equation we will create one measure ; one for Ending Value, Beginning Value and # of Years.  On the Home ribbon click the button labeled New Measure.  Enter the following equation for the beginning value:

    Beginning Value = CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MIN('World GDP'[Year])))

    This equation totals all the items in the table called World GDP in the column labeled GDP.  This calculation will change based on the selections in the page view.

    Add two more measures for Ending Value and # of years

    Ending Value = CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MAX('World GDP'[Year])))
    # of Years = (MAX('World GDP'[Year])-MIN('World GDP'[Year]))

    Your fields list should now look like the following:

    Fields List with Measures
    Fields List with Measures

    Next add a Card visual for each new measure we added.  A measure is illustrated by the little calculator image next to the measure.  I have highlighted the Ending Value measure as a card for an example.

    Ending Value Measure as Card Visual
    Ending Value Measure as Card Visual

    Combining all the previous measures we will now calculate the CAGR value.  Add one final measure and add the following equation to calculate CAGR:

    CAGR = ([Ending Value]/[Beginning Value])^(1/[# of Years])-1

    This calculation uses the prior three measures we created.  Add the CAGR as a card visual to the page.

    Card Visual for CAGR
    Card Visual for CAGR

    Notice how the value of this measure is listed as a decimal, which isn’t very useful.  To change this to a percentage click on the measure CAGR item in the Fields list. Then on the Modeling ribbon change the format from General to Percentage.

    Format Change to Percentage
    Format Change to Percentage

    This changes the card visual to now be in a percentage format.

    Percentage Format
    Percentage Format

    Now you can add some fun visuals to the page and depending on what is selected the CAGR will change depending on the selected values.

    ProTip: To calculate the CAGR you can alternatively compute the entire calculation into one large measure like so:

    CAGR = ( [Ending Value] / [Beginning Value] )^(1/ [# of Years] )-1
    
    is the same as below:
    
    CAGR = (  CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MAX('World GDP'[Year])))  /  CALCULATE(SUM('World GDP'[GDP]),FILTER('World GDP','World GDP'[Year]=MIN('World GDP'[Year]))) ) ^ (1/  (MAX('World GDP'[Year])-MIN('World GDP'[Year]))  )-1

    A final recommendation is to wrap the CAGR calculation in an IFERROR function to make sure if one year is selected the measure doesn’t fail.  This returns a 0 if there is a calculation error of the equation. Documentation on IFERROR is found here.

    CAGR = IFERROR( ([Ending Value]/[Beginning Value])^(1/[# of Years])-1 , 0)

    To finish out the tutorial you can add the following visuals:

    Stacked Bar Chart Visual
    Stacked Bar Chart Visual – GDP by Year
    GDP by Country
    Stacked Bar Chart Visual – GDP by Country

    Note: you can sort the items in the stacked bar chart by selecting the ellipsis (the three dots in the upper right hand corner) and then selecting Sort By and clicking GDP.

    Country Sorted by GDP
    Country Sorted by GDP

    Finally select different items in the GDP by Year chart or the GDP by Country chart.  To select more than one item in the bar charts you have hold shift and left mouse click the multiple items.  Notice how all the measures change.

    Years 2013 & 2014 CAGR
    Years 2013 & 2014 CAGR

    Thanks for following along.

    This tutorial used the following materials:

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Calculating a Sum

    Measures – Calculating a Sum

    Often there are times when you will want to display a totals.  Using measures to calculate a total are extremely easy to use.  The power of using a measure is when you are slicing and selecting different data points on a page.  As you select different data points the sum will change to reflect the selected data.  See sample of what we will be building today below.

    Materials for this Tutorial are:

    • Power BI Desktop (I’m using the April 2016 version, 2.34.4372.322) download the latest version from Microsoft Here.
    • CSV file with data, download SampleData in CSV format.

    To load the CSV file into Power BI Desktop you can follow along in this tutorial, Import CSV File into PowerBI Desktop.

    Once you’ve loaded the CSV file into Power BI Desktop your fields items should resemble the following:

    Fields List
    Fields List

    Add the Table visual from the visualizations bar into the Page area.  Drag the following items into the newly created table visualization, Category, Sales, and ID.  Your table should look like the following:

    Table of Data
    Table of Data

    Click the Triangle next to the ID column under the Values section in the Visualization bar.  A menu will appear, select the top item labeled Don’t Summarize.

    Do not Summarize Data for ID
    Do not Summarize Data for ID

    This reveal all the unique items in our table of data.  Now, we will create our measures for calculating totals.  On the Home ribbon click the New Measure button.  Enter in the following DAX expression.

    Total Sales = SUM(SampleData[Sales])

    Note: In the equation above everything before the equals sign is the name of the measure.  All items after the equation sign is the DAX expression.  In this case we are taking a SUM of all the items in the Table SampleData from the column labeled Sales.

    This will total all the items in the sales column.  Click on the Card visual and add the Total Sales measure to the card.  Your new card should look like the following.

    Total Sales Measure
    Total Sales Measure

    Next we will add a bar chart to show how the data changes when the user selects various items on the page to filter down to different results.  Add the Stacked Bar Chart to the page.  In the Axis & Legend selectors add the Category column, and add the Sales column to the Value selector.  This will yield the following bar chart.

    Bar Chart
    Bar Chart

    Now we can click on items in the bar chart to see how the table of data and the Total Sales changes for each selection.  Clicking on the bar labeled Apples provides a total sales of 283, and clicking on the Oranges shows a total of 226.

    Apples Bar Selected
    Apples Bar Selected

    Our measure is complete.  Now we can select different visualizations and each time we do PowerBI is filtering the table of available data down to a smaller subset.

    Pro Tip: When building different visuals and measures often it is helpful to have a table showing what data is being filtered when you interact with the different visuals.  Sometimes the filters that you are applying by clicking on a visual interact in non-expected ways.  The table helps you see these changes.

    We have now completed a measure that is calculating a total of all the numeric values in one column.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

  • Measures – Calculating % Change

    Measures – Calculating % Change

    In our last post we built our first measure to make calculated buckets for our data, found here.  For this tutorial we will explore the power making measures using Data Analysis Expressions (DAX).

    When starting out in Power BI one area where I really struggled was how to created % change calculations.  This seems like a simple ask and it is if you know DAX.

    Alright lets go find some data.  We are going to go grab data from Wikipedia again.  I know, the data isn’t to reliable but it is fun to play with something that resembles real data.  Below is the source of data:

    https://en.wikipedia.org/wiki/Automotive_industry

    To acquire the data from Wikipedia refer to this tutorial on the process.  Use the Get Data button, click on Other on the left, select the first item, Web. Enter the webpage provided above in the URL box.  Click OK to load the data from the webpage.  For our analysis we will be completing a year over year percent change.  Thus, select the table labeled By Year[edit].  Data should look like the following:

    Global Auto Production Wikipedia
    Global Auto Production Wikipedia

    This is the total number of automotive vehicles made each year globally from 1997 to 2014.  Click Edit to edit the data before it loads into the data model.  While in the Query Editor remove the two columns labeled % Change and Source.  Change the Name to be Global Production.  Your data will look like the following:

    Global Production Data
    Global Production Data

    Click Close & Apply on the Home ribbon to load the data into the Data Model.

    Add a quick visual to see the global production.  Click the Area Chart icon, and add the following fields to the visual, Axis = Year, Values = Production.  Your visual should look something like this:

    Area Chart of Global Production
    Area Chart of Global Production

    Next we will add a table to see all the individual values for each year.  Click the Table visual to add a blank table to the page.  Add Both Year and Production to the Values field of the visual.  Notice how we have a total for both the year and production volumes.  Click the triangle next to Year and change the drop down to Don’t summarize. 

    Change to Don't Summarize
    Change to Don’t Summarize

    This will remove the totaled amount in the year column and will now show each year with the total of Global Production for each year.  Your table visual should now look like the following:

    Table of Global Production
    Table of Global Production

    Now that we have the set up lets calculate some measures with DAX.  Click on the button called New Measure on the Home ribbon.  The formula bar will appear.  We will first calculate the total production for 2014.  We will build on this equation to create the percent change.  Use the following equation to calculate the sum of all the items in the production column that have a year value of 2014.

    Total 2014 = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2014))

    Note: I know there is only one data point in our data but go alone with me according to the principle.  In larger data sets you’ll most likely have multiple numbers for each year, thus you’ll have to make a total for a period time, a year, the month, the week, etc..

    This yields a measure that is calculating only the total global production in 2014.  Add a Card visual and add our new measure “Total 2014” to the Fields.  This shows the visual as follows, we have 90 million vehicles produced in 2014.

    2014 Production
    2014 Production

    Repeat the process above instead use 2013 in the Measure as follows:

    Total 2013 = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2013))

    This creates another measure for all the production in 2013.  Below is the Card for the 2013 Production total.

    2013 Production
    2013 Production

    And for my final trick of the evening I’ll calculate the percent change between 2014 and 2013.  To to this we will copy the portions of the two previously created measure to create the percent change calculation which follows the formula [(New Value) / (Old Value)]- 1.

    % Change = CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2014)) / CALCULATE(sum('Global Production'[Production]),FILTER('Global Production','Global Production'[Year] = 2013)) - 1

    This makes for a long equation but now we have calculated % change between 2013 and 2014.

    Percent Change
    Percent Change

    Wait you say.  That seems really small, 0.03 % change is next to nothing.  Well, I applaud you for catching that.  This number is formatted as a decimal number and not a percentage, even though we labeled it as % change.  Click the measure labeled % Change and then Click on the Modeling ribbon.  Change the formatting from General to Percentage with one decimal.  Notice we now have a percentage.

    Change Format to Percentage
    Change Format to Percentage

    Thanks for working along with me.  Stay tuned for more on percent change.  Next we will work on calculating the percent change dynamically instead of hard coding the year values into the measures.

    Want to learn more about PowerBI and Using DAX.  Check out this great book from Rob Collie talking the power of DAX.  The book covers topics applicable for both PowerBI and Power Pivot inside excel.  I’ve personally read it and Rob has a great way of interjecting some fun humor while teaching you the essentials of DAX.

    Please share if you liked this tutorial.

  • Manually Enter Data

    Manually Enter Data

    There are often times when you need a small data set in order to make a visual behave exactly how you want it to.  This may mean you need a small table to represent a range of numbers or text values.

    Here are the Resources for this tutorial:

    • Power BI Desktop (I’m using the March 2016 version, 2.33.4337.281) download the latest version from Microsoft Here.

    To enter your own data Click the Enter Data button on the Home ribbon.

    Enter Data
    Enter Data Button

    Next you are prompted with the Create Table window.  In this window you are given the layout of a unfilled table.  To begin entering data you can click in the first cell in Column one and start entering data.  By pressing enter a new cell will populate below.  You can Rename the column by double clicking the column name.  To add a second column you Click on the symbol next to your existing column.  Finally to edit the table name you can type in the desired table name in the Name input box in the bottom left hand portion of the window.

    Create Table
    Create Table Window

    Finally, you can either to choose to Load the data as is or Edit the data to make additional changes (this can be useful to edit the data types of each column or to populate equations in subsequent columns).  For the sake of this tutorial we will simply load the data.  Click Load to load the data into the data model.

    Now drag over the columns into the page view to begin generating visuals.  By default PowerBI makes a table of data to show you the values you just entered.

    Sales Table
    Visual of Sales Table

    Select the table visual (you know it is highlighted when it has the trim boarder as shown above) and Click the Doughnut Visual.  This transforms the data into a doughnut, and who doesn’t like a nice data doughnut?  Click anywhere in the page to de-select the new doughnut visual.  Add a second table by dragging over he Region and Sales columns.  We can now see the pretty graphic and the numbers supporting that visual.

    Visuals
    Visuals Made with our Custom Data

    I bet you didn’t notice that something changed here.   Look closely at the data we see now vs. what we entered earlier.  Go ahead, scroll up, I’ll wait…  Did you catch it?

    We now have 5 rows of data but we entered 6 before.  That is because the Sales column is a number column and can be aggregated.  Look in the fields column and you see there is a little sum symbol in front of the Sales column.  This means that this column has a default summarization associated.  To see what is the default summarization highlight Sales by clicking on the column name in the grey area.  Then Click the ribbon titled Modeling, and there it is in the properties section the Default Summarization is Sum.  Every time you use the Sales column it will be summarized in the tables and visuals views.  Our visual table shows Brazil with a total sales of 600, because we had two Regions labeled as Brazil 500 and 100.

    Now you can click on any of the data points in the doughnut.  Notice the table automatically filters down to only show the areas you selected.

    Brazil Data
    Data Filtered to only Brazil

    ProTip: you can select multiple selections by holding down CTRL and selecting multiple items in the visual.  You can only do this inside of one visual.  As soon as you click another visual all filtering will disappear.

    Again, I hope you enjoyed this quick tutorial. If you liked it make sure you share it below.

  • Query Settings – Fixing a Missing File

    Query Settings – Fixing a Missing File

    One of the most important concepts to learn within Power BI Desktop is how to build a Data Model.

    Note: In simple terms the Data Model is data that is collected from the get data function.  In your data model you can build multiple queries.  This data is stored in the file.  The data storage is very efficient as the data compressed down to approximately a 4:1 ratio.  1000 KB file will compact down to approximately 250 KB when loaded into Power BI.  From my current understanding all data is loaded into the memory of the computer.  Thus, if you are having performance issues it could be in part due to the RAM of your computer.  

    As you begin to craft more data models you will learn little tips and tricks along the way to make an efficient Data Model for your visualizations.  I have found that the most challenging part of building the data model is structuring the data in a way that will make your selected visual make sense.  This may mean you need to add a measure or a calculated column or a ranking to a data set. Alright lets get started.

    Here are the Resources for this tutorial:

    • Power BI Desktop (I’m using the March 2016 version, 2.33.4337.281) download the latest version from Microsoft Here.
    • We are going to work through the Power BI Desktop file that we built in the Loading Excel Files Into Power BI Tutorial.  You can follow the link to create the Power BI Desktop (pbix) file in the tutorial.  For convenience, the completed file can be downloaded here: Import Excel Tutorial.

    I’m going to start off by extracting the Import Excel Tutorial.zip file to my desktop.  Once the file has been extracted we can open the containing folder.  In this folder there are two files the source data in the excel file and the Power BI Desktop file.

    Note: A Power BI Desktop file has a .pbix file format ending.

    Open the Import Excel.pbix file.  First click the Home ribbon and then click the Refresh button.  Most likely there will be an error similar to the following message.

    Can't find file
    Message box when file can’t be found

    This type of message occurs when you refresh a query and the file is missing or can’t be found.  This is because when i originally built the Power BI Desktop tutorial the excel file that is supply the information was located on my desktop.  This is a common problem when you build connections to local files stored on your computer.  If you move a file into a different folder then the connection will break.

    To resolve this close the message window by clicking Close. on the Home ribbon click the Edit Queries button.  The Query Editor window will be presented.  In a large yellow bar in the data view portion of the window (circled in red) is the error message.

    Note: Circled in blue is the Query Settings window.  This window is the window for all the applied steps to transform the data.  You can change the name of the query in the name box.  From the view we have selected we can see that the step entitled Changed Type is currently selected (seen circled in blue).

    Click the grey button labeled Go To Error which is found in the yellow error box.

    Go To Error
    Error seen inside Query Editor

    Upon clicking the Go To Error button the selection in the Query Settings button to the Source Step.  This is where the query has failed.  More information about the failure is shown in another yellow error box.  This time click Edit Settings in the error box.

    Edit Settings
    Edit Settings in Error window

    Now we have the Load Excel file window prompt open.  In this window Click Browse, navigate to where you extracted all the files downloaded earlier in the tutorial and select the excel document entitled Book1.  Click Open and the new file location will be loaded into the Load Excl Window.  Click OK to complete the settings change.

    New File Location
    New File Location

    Now the data is correctly loaded into the data model.  Notice we are still on the step called Source.  Take some time to click through each step, Source – Navigation – Promoted Headers – Changed Type.  As you click on each step you can see how the data is transforming.

    To see the code that is being used to make each step click the View ribbon and check the little box entitled Formula Bar.  This will make a formula bar appear.  When you click on a step the formula bar will reveal the code needed to complete the selected step.

    Toggle the Formula Bar
    Toggling on the Formula Bar

    We can now see the equation, which is similar to how you would write an equation in excel.  The code in the Changed Type step is here:

    = Table.TransformColumnTypes(#"Promoted Headers",{{"ID", Int64.Type}, {"Sales", Int64.Type}, {"Category", type text}})

    The equation is using the M language to transform the data.  More information on the usage of the M language can be found here.

    Note: Couple of pointers about the data shown in the formula.  The function is called Table.TranformColumnTypes.  The source of the data is a variable called #”Promoted Headers”.  The pound sign and the words following in quotations is how the M language passes variables that have a space contained in the language.  Since the prior step has the name “Promoted (space) Headers” the program has to add the pound sign and the quotation marks.  If there is no space in the naming convention such as “PromotedHeaders” then only the PromotedHeaders would be seen in the code and the pound sign and quotes will be gone. See modify coded when I remove the space from the Promoted Headers applied step.

    = Table.TransformColumnTypes(PromotedHeaders,{{"ID", Int64.Type}, {"Sales", Int64.Type}, {"Category", type text}})

    Notice the the pound sign and quotations are missing.

    The second part of the formula is an array which has been written out in curly brackets:

    {
    {"ID", Int64.Type}, 
    {"Sales", Int64.Type}, 
    {"Category", type text}
    }

    I changed the code by adding line returns to make it easier to read.  The coded array has beginning bracket and an ending bracket.  Each parameter is contained in it’s own curly brackets and separated with a comma.  The array is a 2 x 3 array, it has 3 rows and two data points on each row, just like a matrix.  The first data point is the column name.  In the first row the column that is being address is called ID.  The data transformation parameter is called Int64.Type.  This means that the data is an integer type 64 bit.  This repeats for each row until all parameters have been addressed.

    So there you go, we have opened up a query repaired it and learned a little about the formula bar.

    As a side note, as you build queries each button press that you make on the various ribbons in the Query Editor will make a minimum of one step the in the Query Editor.

    Hope you enjoyed this short tutorial about the Query Editor.  Make sure you share below if you liked it.

  • Folder of Files Loaded to Power BI Desktop

    Folder of Files Loaded to Power BI Desktop

    Ok, I’ve got to be honest the first two tutorials (Loading Excel Files, Loading CSV Files) were only there to get things kicked off. Now we are getting to some of the good stuff.

    When I first saw this feature in Power Query for excel I nearly had a conniption.  My first thought is this is going to CHANGE EVERYTHING, and to be perfectly honest it has. My entire view of Excel and Power BI has been shaped by this simple but powerful idea; Automated Data Loading.

    In all my years as an engineer I would have to constantly copy and paste data from one excel file to another. Then perform some transformations just to produce a bar chart or a line graph, uggh.  This is slow and boring.  I was really good at being boring, and I felt like I was able to become quite ingenious by writing macros and automating parts of my data transformations.  Now I have seen the light,  The simple ability of being able to load a group files from a folder is AWESOME!  Had I had this feature in my engineering days I could have saved so much time.  So in true homage of my engineering roots this post is for you, the all mighty data hungry engineer.

    Alright, enough of be babbling, Lets get to it.

    Materials for this Tutorial:

    • Zip file with (3) three excel files download Data Set.
    • Power BI Desktop (I’m using the March 2016 version, 2.33.4337.281) download the latest version from Microsoft Here.

    Lets start off by downloading the Data Set and unzipping the file to a folder called DataSet.  For this demo I unzipped the files to my desktop folder.

    UnZipped Files
    Location for UnZipped Excel Files

    Next we will open up Power BI Desktop.  On the Home ribbon select the Get Data button.  The Get Data window will be presented and this time we will select the Folder icon in the menu.

    Get Data Folder
    Get Data Folder Icon Selection

    Click the Connect button at the bottom right of the screen.  A folder window will display.  This is where we will select the location of our data in the folder we unzipped earlier.  Click OK once you’ve selected the location of the folder.

    Folder Path
    Folder Path Location

    The next window to open shows the files that Power BI Desktop is able to see in the folder location.  Normally we would press Load and move forward but in this case we want to further manipulate our query to load the data.  Therefore, Click the Edit button to modify the query to load data.

    Folder Location
    View of Files in Selected Folder

    We are now in the Query Editor.  This is where we can manipulate the incoming data before we visualize it.

    Note:  The Query Editor is a graphical representation of the M-language which is used to load data.  Each button press in the Query Editor performs a transformation to your data.  Each step writes a little line of code that handles the transformations.  To see the code Click the View ribbon then click the button labeled Advance Editor.  For more documentation on the M language look at the Microsoft documentation located here.

    Here is an image of the files we loaded in from our folder location in the Query Editor.

    Query Editor
    View of Query Editor

    The next step is to combine all the files into one combined data model.  To do this click the Double Down Arrows that are circled in red on the left side in the column called content.  

    Note: I also circled the Query Settings in Red on the right.  The Query Settings window will become very useful, especially when trouble shooting a query.  You will notice as we make additional data transformations more steps will accumulate in the query settings.

    We now have a final view of all the data from each of the three CSV files.

    Data Model
    Loaded Files into the Data model

    The file needs a little clean up to remove some unwanted data rows.  Notice now that we have loaded all three files.  In each file we had a header row.  Now in our data model we have three rows with headers.  We want to use the first row as column names.  To do this, Click the Use First Row as Headers button on the Home ribbon.

    Header Row
    Use First Row as Headers

    Also, notice there are rows of data that contain the initial header rows from the other two files.

    Other Headers
    Header Rows from Other Two Files

    Now we will apply a filter to remove these rows.  Click the Arrow in the ID row.  This will present a menu.  There are various transformations on this screen, you can sort a row in Ascending, or Descending order, Filter out text items, etc…

    Filter ID Row
    Filter for ID Row

    Click Text Filters and select Does Not Equal and enter ID into the filter.  Click OK to proceed. This will add a step to remove any row that had ID listed in the ID column.

    Filter Rows
    Filter out the Text “ID” from column

    We have transformed our data and now have cleaned the data and it’s ready for use.  Click Close and Apply to load the data to the data model.  Now the data is ready for visualizations.  Thanks for following along.

    Make sure you take some time to share if you enjoyed this tutorial.

  • Import CSV file to Power BI

    Import CSV file to Power BI

    This post is going to be similar to my previous post about Getting Data.  I figure we better cover some of the basics before going crazy with deeper topics.

    Materials for this tutorial:

    • CSV file with some random data, linked here: SampleData in CSV format
    • Power BI Desktop (I’m using the March 2016 version, 2.33.4337.281)

    After I read the previous version I thought it would be helpful to put the materials up at the top and what version I was using.  If you didn’t know Microsoft has been very active in the development of PowerBI.com and Power BI Desktop.  Right now there are weekly updates to PowerBI.com and monthly updates to Power BI Desktop.

    Starting off like before here is a sample of the data from the csv file.  I’m showing the data in notepad to prove it is a comma separated value file (hence the CSV name).

    csvfile
    CSV File opened in Note Pad

    Alright, lets go get some data.  Open up Power BI Desktop.  Click on the Home ribbon.  Select the Get Data icon.

    Get Data Button
    Button for Get Data

    Now the Get Data window will open.  Next, select the second item labeled CSV from the top of the list on the right.

    Get CSV selection
    CSV selection in the Get Data screen

    Click the Connect button at the bottom right hand of the Get Data screen to proceed to the next screen.  Now the open window will let you navigate to the CSV file you would like to import.  Click the Open button at the right of Open window to load the CSV file.  Finally you’ll be presented with the data view of the contents contained inside your CSV file.

    View Of CSV Data
    View of CSV Data file

    Once loaded we now have our view of all the columns of data in the Fields viewing pane on the right.  From here we can build our visuals.

    Loaded CSV Columns
    Loaded Columns from CSV file load

    Now, lets throw together a quick visual of the data.

    Start by clicking the check box next to the label titled Category and then click the box next to the label titled Sales.  This will automatically populate a table with the categories in the first column and the sales for each category in the second column.

    Table Visual
    Table of Data

    To open up the Visualizations bar click on the word Visualizations.  This will present all the information relating to the visuals. Upon opening up the visualizations pane there is a small yellow square showing you which visual is selected.

    Selected Visual
    Showing the Selected Visual

    Note: The blue pen highlighting shows the selected visual on the page.  As you build more complex visuals there will be multiple visualizations on your page.  When you select a specific visual, all the properties in the Visualizations Bar show all the properties for the selected visual.  The Table visual is highlighted by the red highlight circle.

    To change our selected visual to a new visual we will simply select a new icon in the Visualizations bar. Click the icon that looks like a pie chart.

    Pie Chart
    Pie Chart Visualization

    Cool, but what if I want more awesomeness on my page.  No problem.  Let’s copy our visual.  You can do this by selecting the visual.  To know it is selected look for the slight grey bar at the top of the visual.

    Gray Bar on Visual
    Gray Bar denoting that visual is selected

    Copy the visual by using Ctrl + C.  Click any where on the white space on the page.  This will deselect the current visual.  Then paste an identical version of the visual by using Ctrl + V.

    Two Visuals
    Copy and Paste of new Visual

    Ta-da! Now we are really getting somewhere.  Two Amazing visuals, well not quite.  Two identical visuals isn’t very compelling.  Lets change one of the visuals to a different visual.

    Select the top visual by clicking on it.  Then select the Stacked Column Chart which is the second icon from the left in the top row.  Selecting this icon will change the visual.

    Bar Chart
    Bar Chart Visual

    And there you have it.  You’ve imported a CSV file and generated two visuals.  Nice job.

    Hope you enjoyed this tutorial.  Leave comments if you have questions or if you want to see something else in a tutorial. If you like what you see please share this post on your selected social network of choice below.