Data model in excel 2013

This blog post is brought to you by Diego Oppenheimer a Program Manager on the Excel team.

I am very happy to be writing this blog post today. Not just because I will be showing you another way Excel can make your data analysis easier but also because I will be introducing the new Data Model and Relationships features that will hopefully change the way you use Excel for data analysis forever.

For those of you who are not familiar with the power and usefulness of Pivot Tables you might want to check out this article (Overview of PivotTable and PivotChart reports) or this training (PivotTable I: Get started with PivotTable reports) . Some of these articles are a bit old but the principles and functionality still apply .

Ok, here we go…

Finding a home

Around this time last year my wife and I were considering purchasing a house in the Seattle area, even if it meant dealing with some of the worst traffic in the US. So like any self-respecting Excel nerd I started a spreadsheet with a table of data that fit our parameters. This data was easy to find on the many real-estate sites out there like Zillow.com or Redfin.com. One thing I noticed though was that none of the these sites by themselves had all the relevant data I wanted to make an informed decision and this is where the Data Model came into play by allowing me to combine data from multiple sources and perform a richer analysis.

You can see what I started with below or just download the workbook for yourself.

clip_image002

My first look at the Data Model

If you open the file above you will see I have a table with a lot of data. The first thing I am going to do is create a PivotTable so that I can sift through it easily. Under the INSERT tab, hit PivotTable and the 
following dialog should pop-up:clip_image004

I have highlighted a new option in the create PivotTable dialog which is to “Add this data to the Data Model”. So what is this Data Model I speak of?

A Data Model is a new approach for integrating data from multiple tables, effectively building a relational data source inside the Excel workbook. Within Excel, Data Models are used transparently, providing data used in PivotTables, PivotCharts, and Power View reports“. Read more here…

In other words, the new Data Model allows for building a “model” where data from a lot of different sources can be combined by creating “relationships” between the data sources. For those of you with some database knowledge this is similar to creating joins between tables, except all the tables live in Excel.

I chose to add this data to my Data Model because I am going to be combining it with data I will get from other sources to make my analysis more complete.

Create the PivotTable

The first thing I want to do is look at the number of houses I have selected by zip code. To do this I drag the ZIP field to ROWS and the LISTING ID field to VALUES. By default, this will give me a SUM of LISTING ID’s, but we want a COUNT. To do this, right click on the header that says SUM of LISTING ID -> Value Field Settings… and change to COUNT. As you can see, I only have to sift through 165 house listings now (L).

I have decided to add a couple more fields to my PivotTable to help with my analysis. I added LIST PRICE, DAYS ON MARKET and SQFT and changed the Value Field Settings to AVERAGE.

At this time my PivotTable looked something like this:

clip_image006

And my Field List like this:clip_image007

So now I have a layout that shows me the number of houses that met my criteria per Zip code and some extra data like Average Price, Square footage and Days on Market (my realtor says this comes in real handy when negotiating).

What do I know about the Zip codes?

One thing I noticed about all of the real-estate listing sites is that they give you a ton of detail about the listing but don’t really tell you much about the neighborhood. I want to better understand the demographics of the Zip codes I have selected.

Good thing there is a marketplace for just this type of inquiry (http://datamarket.azure.com). This place is great, and you can read all about it here. Make sure you have a Microsoft/Live-ID or sign up for one free.

Type “Demographics” in the search box and find a data set called “2010 Key US Demographics by ZIP Code, Place and County (Trial)”. If I click on that link to the data set, the first option is to “Explore Data Set” and that’s exactly what I want to do.

Next step is to narrow down the data set to only what is relevant, so I make GeographyType: Zip code and StateAbbreviation “WA” and hit “RUN QUERY”. Great, I think I have now what I need.

clip_image009
To get this into Excel you’re going to need two things from this website, so copy these somewhere:

(1) The URL for the current expressed query

(2) Your private account key

Now that I have all of this figured out, I can easily add what I found to the Data Model. In Excel, go to the DATA tab and select “From Other Sources”, “From Windows Azure Marketplace”.

Fill out the information with what you have saved from the website:

clip_image010

clip_image011
Select that table.

Hit “Finish” and then select “Only Create Connection”:

clip_image012

Note: Some of you might be wondering why I chose “Only Create Connection”. I chose to do so, so that the data was never brought onto the Excel sheet, but directly into the Data Model. I only plan on using it in combination with my original table so there was no need to bring it in as a table onto my sheet or create a new PivotTable or PivotChart. If you’re wondering what that PowerView Report does check out this post by Sean Boon.

Combining my Data

If I go back to my original PivotTable, specifically back to the field list, you might have noticed a small change, particularly around the top.clip_image013

You can see a tab called “Active” (which is selected) and a tab called “All”. The field list is the best way to explore our newly created Data Model, and the “All” tab lets us do just that. Any connection or table that was added to the Data Model will show up in this tab. Let’s take a look.

clip_image014

We can see that our original Table (Table 1) and the Table we brought in from the Data Market are both there. Great!

Now for some magic. I want to know a bit more about each of my Zip Codes, so what I am going to do is add those fields from the demog1 table to my PivotTable. The first one I’ll add is MedianAge2010 (we want to live around people our age so we have a better chance of meeting neighbors we have something in common with).

There are two things to notice here. First, the median age is the same for every zip code, which gives me a hint that something is wrong:

clip_image016

And second, a little message popped up in the field list.

clip_image017

Excel is telling me that a relationship between the two tables might be needed, so I go ahead and create it.

clip_image019

A couple of things to notice when working with relationships:

· Both columns chosen need to contain the same type of data (Zip Code in this case).

· They only work when one of the table’s columns contains unique values.

· The Related Column (Primary) should always be the one containing the unique (no duplicates) values.

· In a PivotTable, to be able to put something from the Related Table on Values you will have to have a field from the Related Table on Rows or Columns.

To satisfy this last condition, I remove ZIP and add GeographyId to Rows. Now my PivotTable looks something like this:

clip_image021

The reason for all those ugly blank spaces is because I have no houses that match my criteria from Table1 for every single Zip Code from the Marketplace data. I can easily filter these out by clicking the downward arrow next to Row Labels, Value Filters, Does Not Equal

clip_image022

Great, now I only have the Zip Codes I care about. I went ahead and added some more fields, conditional formatting and some sorting to figure out what the best zip code for us is and ended up with this:

image

Seems like 98103 is a really good candidate, falling in the middle in price and Average SQFT but towards the bottom in both Unemployment and % Vacant units. I can go ahead and add a COUNT of ListingIDs and see that I have 8 houses to go check out in this neighborhood that meet my criteria.

More Details on the Data Model

In this last example, I really am only scratching the surface of what the Data Model can do and I plan on showing much more in future blog posts. Here are some quick facts though:

  • Any given workbook will only have one Data Model.
  • Any table in Excel can be added to the Data Model.
  • Almost all Data Sources can be added to the Data Model (SQL, Odata, Atom feeds, Excel tables and more).
  • Tables in the Data Model have no limit in terms of rows.
  • Relationships can be defined across multiple tables.

I hope this is enough information to make you dangerous with the new Data Model capabilities. Feel free to leave your questions and comments below or message me on Twitter @doppenhe.

Creating a PowerPivot Data Model in Excel 2013

Exploring self-service BI in Microsoft Excel 2013

Self-service business intelligence (BI) is not new to Microsoft Excel. Since Excel S2000, users have been able to connect to an Analysis Services cube to explore data by using PivotTables and PivotCharts. In Excel 2010, PowerPivot was introduced as an add-in based on SQL SERVER TECHNOLOGY. PowerPivot permitted users to import data from a variety of sources and develop a model defining relationships and calculations so that users could then explore by using PivotTables and PivotCharts. In Excel 2013, PowerPivot is still available with some new capabilities, but several other features in Excel make exploring and interacting with data even easier: Excel Data Model, Power Query, Power View, and Power Map.

Get ahead in your career by learning SQL Server through Mindmajix SQL Server Training.

Excel Data Model and PowerPivot

A Data Model is a new approach for integrating data from multiple tables, effectively building a relational data source inside an Excel workbook. Within Excel, Data Models are used transparently, providing tabular data used in PivotTables, PivotCharts, and Power View reports.

In Excel 2013, PowerPivot is built into Excel, so you aren’t required to download and install the add-in, but this applies only to specific versions: Office Professional Plus 2013, Office 365 Professional Plus, and the standalone edition of Excel 2013. When Power BI was announced as a new service for Office 365, PowerPivot was rebranded as Power Pivot, although for now, this new name appears only in online documentation because rebranding occurred after Excel 2013 was released. All references in the product’s user interface continue to display PowerPivot. Nonetheless, from this point forward in this tutorial, we use the new name, Power Pivot.

As part of the integration of Power Pivot into Excel, a type of object called a Data Model was also introduced. You can think of this object as a light version of Power Pivot. It provides storage for data that you import and contains metadata about that data, such as relationships between tables, but it does not contain enhancements to the data, such as calculated columns or column properties that require Power Pivot features. On the other hand, it does use the same built-in xVelocity engine (formerly known as Vertipaq) that was added to Excel 2010 to support Power Pivot. This means that your data is stored in a highly compressed, columnar, in-memory format that is efficient to QUERY.

Related Article: MS Excel Interview Questions

Working with the Data Model

A Data Model is created when you select the Add This Data To The Data Model check box in the Import Data dialog box. This checkbox is automatically selected, without the option to clear it, when you import multiple tables with one connection. However, if you import only a single table, then the check box is not selected, and you must explicitly select it to add the table data to the Data Model.

Import Data dialog box

Figure 4.1: The Import Data dialog box with the Add This Data To The Data Model check box selected.

You can continue to import data from other sources and add that data to the Data Model. If you import data without adding it to the Data Model, you can add it later. To do this, first, highlight the cells that you want to add or place your cursor in one of the cells of a table or named range that contains your data. Next, click Add To Data Model on the Power Pivot tab on the ribbon or click PivotTable on the Insert tab and then select the Add This Data To The Data Model checkbox in the Create PivotTable dialog box.

Note: There is only one Data Model per Excel workbook.

When you have multiple tables in the Data Model, you can import relationships, when you import the tables from a relational source as a group. Otherwise, you can manually define the relationships between tables when you want to include data from them in a single report. Click Relationships on the Data tab to open the Manage Relationships dialog box, and then click New. Select the table containing the foreign column (that is, the column with values repeating across multiple rows) and the foreign column in the top row, and then select the related table and primary column (that is, the column with distinct values only), as shown in Figure 4.2.

The tables and fields that you add to the Data Model are visible in the Field List when you add a PivotTable, a PivotChart, or a Power View report to the workbook. The result is the same if you import data by using Power Pivot features and then define relationships. The key difference between the Data Model and Power Pivot is the inability to rename tables and columns or use the advanced modeling features of Power Pivot when your data is in the Data Model only. However, the Data Model is an easy way to start interactively exploring data without much effort. You can always open the Power Pivot interface to apply Power Pivot features to the model if additional refinement proves necessary.

Create Relationship dialog boxFIGURE 4.2: Create Relationship dialog box displaying a selection of tables and columns for a new relationship.

After building your first PivotTable or other types of a report based on the Data Model, you can create another report based on the same Data Model. On the Insert tab, click PivotTable. Then, in the Create PivotTable dialog box, select Use An External Data Source, click Choose Connection, click the Tables tab, and select Tables In Workbook Data Model, as shown in figure 4.3.

Existing Connections dialog box
FIGURE 4.3: The Existing Connections dialog box displaying the selection of Tables In Workbook Data Model.

Frequently Asked SQL Server Interview Questions & Answers

Managing data as a Power Pivot model

Power Pivot Management Dashboard is a collection of predefined reports and web parts in SharePoint Central Administration that help you administer a SQL Server Power Pivot for SharePoint deployment.

When you need to refine the Data Model in some way, you need to use Power Pivot. You might do this when you need to import a subset of data. Power Pivot allows you to select specific columns for import or to apply a filter to import a selected set of rows. After you import data, you can rename tables and columns, create relationships, and add formatting to improve the display of data in reports. You can also enhance the data with calculations to perform arithmetic or statistical operations or even to cleanse the data, such as replacing empty values with a default string or number.

 MindMajix YouTube Channel

The SQL Server 2012 release of Power Pivot for Excel is available as a downloadable add-in for Excel 2010, but it is built directly into Excel 2013. In either version of Excel, Power Pivot must be enabled. To do this, click Options on the File tab in Excel, select Add-Ins in the navigation pane of the Excel Options dialogue box, select COM Add-ins in the Manage drop-down list, click the Go button, and select the Microsoft Office PowerPivot for Excel 2013 (or 2010) check box.

The latest release of Power Pivot in Excel 2013 works much like it did when it was introduced as a part of SQL Server 2008 R2, as an add-in for Excel 2010. However, the workbook size limitation has been removed from the 64-bit version of Excel, which means your workbook can be as large as the amount of disk and memory as your computer permits. As you might expect, there are several new features, some changed features, and a few features that have been removed, as described in the following list:

Related Page: SQL Server 2008 R2 – LookUp Enhancement In SSRS

Calculated fields Instead of right-clicking a table in the Field List to add a calculated field (previously called a measure), you click Calculated Fields on the Power Pivot tab (although you can still create a calculated field in the Calculation Area in the Power Pivot window).

Perspectives, in tabular models, define viewable subsets of a model that provide focused, business-specific, or application-specific viewpoints of the model. The list of available perspectives is no longer available at the top of the Field List. Now you can use perspectives to view a subset of the model only when you have the Power Pivot window open. If you publish your workbook to Power Pivot for SharePoint, you can create a connection string that uses the perspective explicitly. In addition to the Data Source and Initial Catalog keywords in the connection string, add Cube=.

KPIs In business terminology, a Key Performance Indicator (KPI) is a quantifiable measurement for gauging business success. In the previous version, you could select a calculated field in the Field List to enable the Create KPI option on the Power Pivot tab. Now you can use the KPIs option to create a new KPI or manage existing KPIs without even making a selection in the Field List, but still having the ability to create a KPI in the Calculation Area in the Power Pivot window.

Descriptions SQL Server stores column descriptions as so-called Extended properties, using the extended property named ‘MS_Description’. You no longer view descriptions for tables, columns, and calculated fields in the Field List when working with a PivotTable or PivotChart. A description is now displayed only as a ScreenTip in the Field List of a Power View report.

Slicers are one-click filtering controls that narrow down the data shown in PivotTables and PivotCharts. Slicers can be used interactively to display data changes when you apply filters. The Slicer is added as an extra control in the PivotTable or chart, and lets you quickly select criteria and instantly show the changes. You could also embed the breakdown by promotion in the report itself, by including the field in the row or column heading, but Slicers do not add extra rows to the table, only provide an interactive view into the data.

The Slicers Vertical and Slicers Horizontal areas are no longer displayed at the bottom of the Field List. Instead, you right-click the field in the Field List and then select Add As Slicer from the submenu. To change the orientation of the slicer, click the slicer to select it, and then click Align Vertically or Align Horizontally on the Power Pivot tab.

Search The Search box has been removed from the Field List. Instead, use the Find option on the Home tab in the Power Pivot window to search for a table, column, or calculated field by name. Full-Text Search in SQL Server and Azure SQL Database lets users and applications run full-text queries against character-based data in SQL Server tables.

Relationships A relationship works by matching data in key columns — usual columns with the same name in both tables. Power Pivot is no longer capable of automatically detecting relationships between tables. You must import relationships when importing a group of tables at one time or manually define the relationships in the model.

Data categorization Data classification is the process of organizing data into categories for its most effective and efficient use. The Advanced tab on the ribbon in the Power Pivot window includes a Data Category list that you use to assign one of the following categories to a column: Address, City, Company, Continent, Country/Region, Country, Date, Image, Image URL, Latitude, Longitude, Organization, Place, Postal Code, Product, State Or Province, or Web URL. Power View uses this categorization to apply the proper visualization to your data where possible. In addition, the Windows Azure Marketplace uses this information to suggest data sources that might be useful to integrate into your Power Pivot model.

Related Page: How To Create A Power View Report In Excel 2013

Upgrading from PowerPivot for Excel 2010

This topic explains the user experience of workbooks created in previous Power Pivot environments and how to upgrade Power Pivot workbooks so that you can take advantage of new features introduced in this release.

To upgrade an existing workbook that was created in Excel 2010, first, open the workbook in Excel 2013. On the Power Pivot tab, click Manage. Excel displays a message explaining that you must upgrade the data model before using Power Pivot for Excel 2013. Click OK to display another message that warns, that the upgraded workbook cannot be used with previous versions of Power Pivot. Click OK to start the upgrade. When the upgrade is complete, another message prompts you to take the workbook out of Excel compatibility mode. Click Yes to save, close, and reopen the workbook and thereby exit Excel compatibility mode.

Explore SQL Server Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

List of Related Microsoft Certification Courses:

About Author

Remy Sharp

Arogyalokesh

Arogyalokesh is a Technical Content Writer and manages content creation on various IT platforms at Mindmajix. He is dedicated to creating useful and engaging content on Salesforce, Blockchain, Docker, SQL Server, Tangle, Jira, and few other technologies. Get in touch with him on LinkedIn and Twitter.

If you’re importing foreign data or sharing a workbook, the data often ends up in several sheets. As a result, turning data into meaningful information can be difficult. That’s where Excel 2013’s new data modeling capabilities can help even casual users. By building a relationship between sheets, Excel 2013 makes summarizing data spread across multiple sheets easy.

Putting this new feature into practice is easy, but it works mostly behind the scenes. As a result, it can be difficult to get a handle on how to implement it. In the next 10 steps, we’ll define a reporting need and meet it using Excel 2013’s new data model.

This article is for users unfamiliar with the feature and trainers supporting Excel users. This feature isn’t for serious database developers, and please don’t blast me for Microsoft’s unfortunate choice for naming this new feature.

1. Defining the need

Figure A shows two sheets with related data. As you can see, each record in Daily Totals contains a value that’s further described by date, personnel, and city. The records in Sites list the cities in each region. Now, suppose you want to total the values in Daily Totals by region.

Figure A

These two sheets contain records that are related.

Working through your data won’t always be this easy. I’ve purposely kept this example simple to keep the focus on the steps.

2. Convert data to tables

To use Excel’s data model, convert the data into tables. When working with your own data, make sure your data set has a row of headers. Our data sets already have a row of headers. To convert data to a table, do the following:

  1. Click anywhere inside the data set and click the Insert tab.
  2. Click Table in the Tables group.
  3. In the resulting dialog box, shown in Figure B, click OK. In this case, the header option is already checked. When applying this technique to your own data, you’ll want to check or uncheck this option, appropriately.

Figure B

Convert your data to a table.

Use the above steps to convert both data sets. Naming the new tables isn’t necessary, but it will make working with them easier. To that end, click inside a table and click the contextual Design tab. Then, enter a meaningful name in the Table Name field, as shown in Figure C. Name them DailyTotalsTable and SitesTable.

Figure C

Named tables are easier to work with.

3. Finding the related data

There’s no regional information in the data set that contains the values you want to summarize. With data modeling, that’s not a problem. All you need is a relationship between the table with the values you want to summarize and the regional data you’ll use to summarize those values. A relationship is a connection between two tables based on a single column in both. In other words, when two data sets share a similar column of data, they are related by that common column. In the case of our example, the City column relates the two data sets.

4. Create the relationship

Creating a relationship between two data sets is new to Excel, but don’t let that worry you—it’s easy. To create a relationship between the two tables do the following:

  1. Click the Data tab.
  2. Click Relationships in the Data Tools group. (If this option is dimmed, return to #2 and create the tables.)
  3. From the first Table dropdown, choose DailyTotalsTable.
  4. In the Column (Foreign) dropdown, choose City.
  5. In the Related Table dropdown, choose SitesTable.
  6. In the Related Column (Primary) dropdown, choose City, as shown in Figure D.
  7. Click OK.
  8. Click Close to return to the sheet.

Figure D

Specify the column that both columns share to create a relationship between the two tables.

5. Generate a blank PivotTable

To summarize the values, we’ll generate a PivotTable. Click inside DailyTotalsTable and click the Insert tab. In the Tables group, click PivotTable. When Excel displays the dialog shown in Figure E, click OK.

Figure E

Generate a blank PivotTable in a new worksheet.

You can use the new Recommended PivotTables option, but it won’t consider your second table, so it’s easier to start with a blank table.

6. Add the second table

Currently, the PivotTable frame evaluates only one table, DailyTotalsTable. Add SitesTable as follows:

  1. Click the MORE TABLES link shown in Figure F.
  2. In the resulting dialog, click Yes. Doing so engages the new data modeling feature.

As you can see in Figure G, both tables are now part of your PivotTable structure.

Figure F

Clicking MORE TABLES will engage the data modeling feature.

Figure G

Both tables are now available to you.

7. Add fields

It’s time to start adding fields to the PivotTable. First, click the expand arrow to the left of DailyTotalsTable to see its fields. Check Value and City. Then, use the scroll bar to access SitesTable. Expand its fields and select Region. Doing so adds these fields to the PivotTable frame, as shown in Figure H.

Figure H

Thanks to the data modeling feature, you can add fields from both tables to the PivotTable frame.

8. Add regions to summarize

At this point, the PivotTable probably won’t be perfect, so it’s time to start tweaking a bit. Figure I shows the result of dragging the Region field to the COLUMNS section.

Figure I

Adding Regions summarizes the values accordingly.

9. A quick switch

If you don’t like that layout, you can quickly switch the column and row headings. Simply drag the City field to the COLUMNS section and the Region field to the ROWS section, as shown in Figure J.

Figure J

Switching the rows and columns is easy.

10. Oops!

If you’re paying close attention, you might have noticed the (blank) row. Can you guess where that came from? By reviewing the city headings for those items, you can quickly troubleshoot the problem. Using Figure A, you can determine that there’s no region value for Boston and Cleveland. Fortunately, it’s a quick fix. Add the values to SitesTable, as shown in Figure K.

Figure K

Add the missing regions for Boston and Cleveland.

After adding the new regional records, refresh the PivotTable. To do so, click inside the table and then click the contextual Analyze tab. In the Data group, click Refresh. Figure L shows the refreshed PivotTable.

Figure L

After refreshing the table, it displays the regional values correctly.

11: Bonus

Did you notice the little magnifying glass icon in Figure L? Clicking that will let you drill deeper into the details that aren’t currently visible. Clicking this icon with the Cleveland value selected, displays the dialog shown in Figure M. Figure N shows the results of drilling to the City, the cities in the Central region.

Figure M

This dialog defaults to SitesTable, but you can switch to DailyTotalsTable.

Figure N

Drilling offers quick access to unseen details without creating a new PivotTable.

To access the demo version of the Excel data used here in the examples, download the Excel file here: http://b2b.cbsimg.net/downloads/Frye/11142013Demo.zip

Introducing the Data Model

One of the new features included in Excel 2013 is the Data Model.  The Data Model is a cut down version of the PowerPivot add-in that was and is still available for Excel 2010 users.  The PowerPivot add-in allows you to combine multiple tables in a PivotTable.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

In Office 2013 the PowerPivot add-in is only available to Office 2013 Professional Plus users – not a licence you can buy retail. However, the Data Model (the cut down version of the add-in), is available to standard Excel 2013 users: this tutorial explains how to use the Data Model to combine multiple, related tables in a Pivot Table.

In many ways the Data Model achieves the same thing as a VLOOKUP: it combines data from multiple sources based on a common field.  The Data Model is probably the way to go if you are working with a lot of records and a lot of fields where working with a VLOOKUP would be more time consuming and awkward.  Anyway, let’s have a look at how to use the Data Model.

The video below will take you through this exercise and you can download the featured file to practice your new found knowledge!

The solution I want to reach using the Data Model concerns these three sets of data. The first contains records of sales transactions

Data in Excel 1

The second set of data assigns a product category to each product

Data in Excel 2

The third set of data tells me which region each branch is in.

Data in Excel 3

I need my PivotTable to show me a breakdown of sales per product category, per region – something I can’t do with the original sales data because the both the product category and region information are missing.

Converting Ranges to Excel Tables

[dropcap type=”circle” color=”#ffffff” background=”#66a3bf”]T[/dropcap]he three sets of data are in the same workbook on different sheets.  To start with I am going to convert each range into an Excel table: this makes the data easier to identify in the Data Model as I can name the tables.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

To convert a range is pretty easy. I just select a cell within the data and then on the INSERT tab on the Ribbon click the Table button.

Convert Range to Table

I then need to click OK to confirm I am happy with range selected.

Confirm Range for Table

Your Excel table will include some formatting and the filter drop-downs for each column: we won’t need the filter functionality but it’s applied anyway.  The important thing to do at this stage is to name the table. You will notice that your Ribbon now includes a Table Tools DESIGN tab.  On the far left of the Ribbon with that tab activated you will see a box where you can enter a name for the table.  By default it will be called Table1.  I named my first table Sales_Data.  Spaces are not allowed in table names so I used an underscore.

Name Excel Table

You need to convert each of your ranges to a table, naming them accordingly.  I named my other two tables Product_Data and Region_Data.

Adding the Tables to the Data Model

[dropcap type=”circle” color=”#ffffff” background=”#66a3bf”]T[/dropcap]he next step is to add my tables to the Data Model.  If I add one of them, they all get added at the same time.

I am going to start off by adding the sales data to the Data Model.  To do this, I click into any cell in the data and then on the INSERT tab on the Ribbon click the Pivot Table button.

Create PivotTable

The important thing here is to check the option that allows you to add the data to the Data Model (see below).

Add Date to the Data Model

Click OK to confirm.

A PivotTable appears on a new worksheet and in the PivotTable Fields list you will notice two buttons: ACTIVE and ALL.  Click on the ALL button and you will see that each table has been added to the Data Model.

View All Fields in the Data Model

Establishing Relationships between the Tables

[dropcap type=”circle” color=”#ffffff” background=”#66a3bf”]A[/dropcap]lthough the fields have been added to the Data Model I still need to establish relationships between the data.

The sales data is related to the product data via the product field (the product names appears in each table).  The sales data is related to the region data via the branch field (again, the branch names appear in both tables).  By establishing a relationships between the two tables I will be able to connect branch with its respective region and product with its respective product category.

5 FREE EXCEL TEMPLATES
Plus Get 30% off any Purchase in the Simple Sheets Catalogue!

The relationships are set up on ANALYZE tab within the PivotTable Tools. Click the Relationships button within the Calculations group as shown below.

Establish Relationships between Tables in the Data Model

In the Manage Relationships dialog, click New and then pick the tables and fields you want to use to establish a relationship.  In the example below I have established a relationship between the Sales_Data table and the Region_Data table using the common Branch field.

Select Columns for the Relationship

You have to get the direction of the relationship right.  Notice the first field you select is called the Foreign column and the second the Primary Column.  In each case with our example the Sales data contains the Foreign key and the other table (region or product) contains the Primary column – the data we are adding to our Sales data.

If you get the direction wrong Excel will let you know and it’s just a matter of swapping the columns around.

The Relationship must be in the right direction

Click on OK to confirm the relationship. I now need to create a relationship between the Sales table and the Product table as shown below.

The second relationship in the data model

With the relationships established I can now close the Manage Relationships dialog and get on with adding fields to my PivotTable.

Creating the PivotTable

[dropcap type=”circle” color=”#ffffff” background=”#66a3bf”]I[/dropcap] need to expand the table buttons in the field list to see my table fields.

Expand the Tables in the Field List

I can now add the fields to the PivotTable as I would normally.  How to add and format fields is another tutorial altogether so I will assume you are already up to that.

To reach my original goal: get a breakdown of sales per region per product category, I arranged my PivotTable as shown below.

PivotTable Configuration

My PivotTable now provides the solution.

The PivotTable using the Data Model

 The Downside

There are a few downsides of using the Data Model:

  • you can’t group fields.  Grouping fields is pretty essential if you are working with date fields
  • you can’t create calculated fields or items
  • you can’t double-click a value in a PivotTable get and see the records that make up that value on a separate sheet

В Excel 2013 появился новый аналитический механизм: модель данных. Каждая рабочая книга располагает собственной внутренней моделью данных, упрощающей анализ разрозненных источников данных. [1] Идея, заложенная в основу модели данных, проста. Предположим, что в вашем распоряжении имеются две таблицы: Заказы (рис. 1) и Сотрудники (рис. 2). В таблице Заказы содержится информация о сделках (код сотрудника, дата и сумма счета-фактуры, период продаж). В таблице Сотрудники находится информация о сотрудниках: код, фамилия, имя и должность. Если нужно проанализировать суммы продаж в зависимости от должности сотрудника, следует объединить информацию, содержащуюся в двух таблицах. Чтобы ваши данные имели вид Таблицы – инструмента Excel(поэтому пишется с заглавной буквы) – кликните на любой ячейке таблицы данных и выполните команду Создать Таблицу: Ctrl+T.

Рис. 1. Информация о сделках

Рис. 1. Информация о сделках

Скачать заметку в формате Word или pdf, примеры в формате Excel

Рис. 2. Информация о сотрудниках

Рис. 2. Информация о сотрудниках

Выполнение подобной задачи в прошлом потребовало бы использования множества формул ВПР, СУММЕСЛИ и других. После появления модели данных в Excel 2013 достаточно объявить обе таблицы связанными (по коду сотрудника) и включить их в модель данных. Модель данных Excel создает куб аналитики на основе связи между кодами сотрудников и передает нужные данные в сводную таблицу.

Наша задача заключается в том, чтобы отобразить суммы продаж в зависимости от должности сотрудника. В прежних версиях Excel решить подобную задачу было непросто, поскольку сведения о продажах и должностях сотрудников находились в отдельных таблицах. После появления модели данных достаточно выполнить следующие действия:

1. Щелкните в области таблицы Заказы и начните создавать новую сводную таблицу, выбрав команду ВставкаСводная таблица.

2. В диалоговом окне Создание сводной таблицы установите флажок Добавить данные в модель данных (рис. 3). Обратите внимание на то, что в окне Создание сводной таблицы находится ссылка на именованный диапазон (Таблицу данных); в нашем примере – Заказы. Рекомендуется присваивать говорящие имена Таблицам данных. Это облегчит распознавание таблиц, находящихся в модели данных. Если не присваивать названия Таблицам данных, модель данных отобразит их под названиями Таблица 1, Таблица2 и т.д. Чтобы назначить Таблице данных имя, кликните на Таблице, перейдите на контекстную вкладку Работа с даннымиКонструктор и в поле Имя таблицы введите говорящее имя. Повторите эту операцию для всех остальных Таблиц.

Рис. 3. Создайте сводную таблицу на основе таблицы данных Заказы

Рис. 3. Создайте сводную таблицу на основе таблицы данных Заказы

3. Щелкните в области таблицы данных Сотрудники и начните создавать новую сводную таблицу. Не забудьте установить флажок Добавить эти данные в модель данных.

4. После добавления таблиц в модель данных перейдите к списку полей сводной таблицы и выберите переключатель ВСЕ. В списке полей появятся два диапазона, соответствующие таблицам данных (рис. 4).

Рис. 4. В списке полей сводной таблицы выберите параметр ВСЕ

Рис. 4. В списке полей сводной таблицы выберите параметр ВСЕ, чтобы получить доступ ко всем таблицам, находящимся в модели данных

5. Создайте сводную таблицу обычным образом. В новой таблице поле Должность появится в области СТРОКИ, а поле Сумма по столбцу Объем продаж — в области ЗНАЧЕНИЯ. Программа тут же распознает, что используются две таблицы из модели данных, и предлагает создать связь между ними (рис. 5). Щелкните на кнопке Создать.

Рис. 5. Выберите создание связи между таблицами после отображения соответствующего запроса

Рис. 5. Выберите создание связи между таблицами после отображения соответствующего запроса

6. На экране появится диалоговое окно Создание связи (рис. 6). В этом окне можно выбрать таблицы и поля, для которых создается связь. На этом рисунке показана таблица Заказы с полем Код сотрудника. Эта таблица связана с таблицей Сотрудники с помощью поля Код сотрудника.

Рис. 6. Создайте подходящую связь, используя раскрывающиеся списки Таблица и Столбец

Рис. 6. Создайте подходящую связь, используя раскрывающиеся списки

7. После создания связи можно использовать данные из двух таблиц для отображения требуемых результатов. Применение модели данных проиллюстрировано на рис. 7.

Рис. 7. Отображение объема продаж по должностям сотрудников

Рис. 7. Отображение объема продаж по должностям сотрудников

Первичные ключи. Обратите внимание на рис. 6 на раскрывающийся список Связанный столбец (первичный ключ). Это означает, что модель данных использует поле, относящееся к связанной таблице, в качестве первичного ключа. Первичный ключ — это поле, содержащее лишь уникальные ненулевые значения (без дубликатов и пустых значений). Первичные ключи применяются в модели данных в целях предотвращения ошибок суммирования и дубликатов. В каждой связи должен быть хотя бы один первичный ключ. Поскольку поле Код сотрудника, находящееся в таблице Сотрудники, является первичным ключом, оно должно включать только уникальные значения (без пробелов и нулевых значений). Первичный ключ обеспечивает единственный способ сохранения целостности данных при объединении нескольких таблиц.

Управление связями в модели данных

После включения таблиц во внутреннюю модель данных может потребоваться настройка связей, установленных между ними. Чтобы изменить связи модели данных, отобразите диалоговое окно Управление связями. Для этого выберите вкладку ленты Данные и в области Работа с данными щелкните на кнопке Отношения. Требуемое окно появится на экране (рис. 8).

Рис. 8. В диалоговом окне Управление связями можно изменить связи, заданные в модели данных

Рис. 8. В диалоговом окне Управление связями можно изменить связи, заданные в модели данных

В этом окне доступны следующие команды, применяемые для изменения связей между таблицами:

  • Создать. Создание новой связи между таблицами модели данных.
  • Изменить. Изменение выделенной связи.
  • Активировать. Активизация выбранной связи, вследствие чего Excel будет рассматривать данную связь при агрегировании и анализе данных в модели.
  • Деактивировать. Отключение выбранной связи. Это приведет к тому, что Excel будет игнорировать связь при агрегировании и анализе данных в модели.
  • Удалить. Удаление выбранной связи.

Добавление новой таблицы в модель данных. Чтобы добавить новую таблицу в модель данных, воспользуйтесь одним из следующих двух способов.

Во-первых, можно создать сводную таблицу на основе новой Таблицы данных (в нашем примере – Местоположения). В окне создания сводной таблицы установите флажок Добавить эти данные в модель данных. Excel добавит Таблицу в модель данных и создаст сводную таблицу. После добавления сводной таблицы можно открыть диалоговое окно Управление связями и создать нужные связи.

Второй (и более гибкий) способ заключается в том, чтобы создать таблицу вручную и добавить ее в модель данных. Выполните следующие действия.

1. Если вы еще не создали Таблицу, поместите курсор в таблицу данных (лист ExcelМестоположения, любую ячейку в диапазоне А1:С55), перейдите на вкладку Вставка щелкните на кнопке Таблица (рис. 9). Можно, встав в ячейку таблицы данных, нажать Ctrl+T. На экране появится диалоговое окно (рис. 10), в котором задается диапазон данных. Нажмите Ok. Программа преобразует этот диапазон в Таблицу, которая может распознаваться внутренней моделью данных.

Рис. 9. Создание Таблицы на основе исходных данных

Рис. 9. Создание Таблицы на основе исходных данных

Рис. 10. Преобразование диапазона в таблицу

Рис. 10. Преобразование диапазона в таблицу

2. На контекстной вкладке Работа с таблицамиКонструктор, измените значение поля Имя таблицы, выбрав легко запоминаемое имя; в нашем примере – Отделения.

3. Перейдите на вкладку ленты Данные и в области Подключения щелкните на кнопке Подключения. На экране появится диалоговое окно Подключения к книге (рис. 11). Щелкните на стрелке раскрывающегося списка, находящейся справа от кнопки Добавить, и выберите пункт Добавить в модель данных.

Рис. 11. Откройте диалоговое окно Подключения к книге и выберите пункт меню Добавить в модель данных

Рис. 11. Откройте диалоговое окно Подключения к книге и выберите пункт меню Добавить в модель данных

4. На экране появится диалоговое окно Существующие подключения (рис. 12). Перейдите на вкладку Таблицы и выделите только что созданную Таблицу. Щелкните на кнопке Открыть, чтобы добавить выбранную таблицу в модель данных.

Рис. 12. Окно Существующие подключения

Рис. 12. В окне Существующие подключения перейдите на вкладку Таблицы, выделите только что созданную Таблицу и щелкните Открыть

5. Все сводные таблицы, созданные на основе модели данных, обновляются с учетом добавления новой таблицы. Не забудьте открыть диалоговое окно Управление связями и создать требуемую связь.

Удаление таблицы из модели данных. Иногда возникает необходимость в удалении Таблицы или источника из модели данных. Чтобы выполнить эту задачу, выберите вкладку ленты Данные и щелкните на кнопке Подключения. На экране появится диалоговое окно Подключения к книге (рис. 13). Выберите таблицу, а затем кликните на кнопке Удалить.

Рис. 13. С помощью окна Подключения к книге можно удалить любую таблицу из внутренней модели данных

Рис. 13. С помощью окна Подключения к книге можно удалить любую таблицу из внутренней модели данных

Создание новой сводной таблицы с помощью модели данных. Иногда приходится создавать сводные таблицы «с нуля», используя в качестве источника данных существующую внутреннюю модель данных. Для этого выполните следующие действия.

1. Выполните команду Вставка → Сводная таблица. Отобразится диалоговое окно Создание сводной таблицы. Установите флажок Использовать внешний источник данных (рис. 14), и щелкните на кнопке Выбрать подключение.

Рис. 14. Окно Создание сводной таблицы

Рис. 14. Окно Создание сводной таблицы

2. На экране появится диалоговое окно Существующие подключения (рис. 15). На вкладке Таблицы выберите параметр Таблицы в модели данных книги и щелкните на кнопке Открыть.

Рис. 15. Окно Существующие подключения

Рис. 15. Окно Существующие подключения

3. Вы вернитесь обратно в диалоговое окно Создание сводной таблицы. Щелкните ОК.

4. Если создание сводной таблицы завершилось удачно, появится панель области задач Поля сводной таблицы, отображающая все таблицы, включенные во внутреннюю модель данных (рис. 16).

Рис. 16. После успешного завершения создания сводной таблицы отображаются все таблицы, относящиеся к модели данных

Рис. 16. После успешного завершения создания сводной таблицы отображаются все таблицы, относящиеся к модели данных

Ограничения внутренней модели данных

Как и все остальное в Excel, внутренняя модель данных имеет определенные ограничения:

Рис. 17. Ограничения внутренней модели данных

[1] Заметка написана на основе книги Джелен, Александер. Сводные таблицы в Microsoft Excel 2013. Глава 7.

Понравилась статья? Поделить с друзьями:
  • Daily life word meaning
  • Daily in the word radio
  • Daily 4 pics one word
  • Data mining для excel
  • Daftar ustiga muqova word