1. Trang chủ
  2. » Công Nghệ Thông Tin

quickstart learn dax basics in 30 minutes

16 217 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 16
Dung lượng 1,04 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Learning nformation you ligence, and DA miliar with creat even if you hav DAX formulas a ecifically on un pts of both calc familiar with th irst step throug alled on your c X is to creat

Trang 2

QuickStart: Learn DAX Basics in 30 Minutes

Owen Duncan

Summary: This QuickStart is for users new to PowerPivot or tabular model projects

authored in SQL Server Data Tools It is meant to give you a quick and easy introduction

on how you can use Data Analysis Expressions (DAX) to solve a number of basic data modeling and analytical problems

Category: Quick Step-By-Step

Applies to: PowerPivot for Excel (all versions), SQL Server 2008 R2, SQL Server 2012 Source: TechNet Wiki ( link to source content )

E-book publication date: May 2012

13 pages

Trang 3

Copyright © 2012 by Microsoft Corporation

All rights reserved No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher

Microsoft and the trademarks listed at

http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of the Microsoft group of companies All other marks are property of their respective owners

The example companies, organizations, products, domain names, email addresses, logos, people, places, and events depicted herein are fictitious No association with any real company, organization, product, domain name, email address, logo, person, place, or event is intended or should be inferred

This book expresses the author’s views and opinions The information contained in this book is provided without any express, statutory, or implied warranties Neither the authors, Microsoft Corporation, nor its resellers, or distributors will

be held liable for any damages caused or alleged to be caused either directly or indirectly by this book

Trang 4

Min

This QuickS

meant to g

number of

you can co

understand

What is DA

DAX is a co

and return

model

Why is DA

It’s easy to

PivotCharts

critical sale

inventory d

important c

data When

line This is

Prereq

You might

understand

you get sta

We are goi

with funda

Help You s

PowerPivot

help, which

Example W

The best w

yourself Th

workbook

downloade

Note:

If you are w

ckStar

utes 

Start is for user

give you a quick

basic data mo

omplete, and a

ding of the mo

AX?

ollection of fun

one or more v

AX so importan

create a Powe

s that display im

es data across s

data from sever

capabilities as w

n you get the in

s Business Intel

uisites

already be fam

ding DAX, but e

arted creating D

ing to focus sp

mental concep

should also be

t, you should fi

h is usually inst

Workbook

way to learn DAX

he examples an

from http://go

ed onto your co

working in the A

rt: Lea  

rs new to Powe

k and easy intro deling and ana few quizzes to

st basic fundam

ctions, operato values Stated m

nt?

rPivot workboo mportant infor several product ral tables in dif well Learning nformation you ligence, and DA

miliar with creat even if you hav DAX formulas a

ecifically on un pts of both calc familiar with th irst step throug alled on your c

X is to create s

nd tasks here u

.microsoft.com

omputer, open

Analysis Servic

arn D

erPivot or tabul oduction on ho alytical problem test what you’

mental concept

ors, and consta more simply, DA

ok and import mation withou

t categories an fferent data sou how to create e

u need, you can

AX will help yo

ting formulas in

ve no experienc and solving rea

nderstanding D ulated column

he PowerPivot

gh the Create Y computer when

ome basic form

se the Contoso

m/fwlink/?LinkID

it, and then op

es tabular mod

DAX Ba

lar model proje

ow you can use

ms This topic in

ve learned Aft

ts in DAX

nts that can be

AX helps you c

some data into

t using any DA

d for different urces? DAX for effective DAX f

n begin to solv

u get there

n Microsoft Exc

ce with Excel fo al-world BI prob

DAX formulas u

s and measure for Excel autho Your First Powe

n the PowerPivo

mulas, use it wi

o Sample DAX

D=237472&clci

pen the PowerP

del project auth

asics i

ects authored in

e Data Analysis ncludes concep

er completing

e used in a form reate new info

o it You can ev

AX formulas Bu date ranges? O mulas provide formulas will he

e real business

cel That knowl ormulas, the co blems right awa

sed in calculati

s, both of whic oring environm erPivot Workbo

ot for Excel add

th some actual Formulas.xlsx w

id=0x409 Once Pivot window

horing environm

 in 30 

n SQL Server D Expressions (D ptual informatio this topic, you

mula, or expres rmation from d

ven create Pivot

ut, what if you n

Or, you need co this capability elp you get the

s problems that

edge will be he ncepts describ

ay

ons You shoul

ch are described ment and tools

ook tutorial incl d-in is installed

l data, and see workbook You

e you have the

ment in SQL Se

 

Data Tools It is DAX) to solve a

on, a series of t should have a

sion, to calcula data already in

tTables or need to analyze ombine importa and many othe

e most out of y

t affect your bo

elpful in

ed here will he

ld already be fa

d in PowerPivo

If you are new uded in Power

d

the results for can download

e workbook

erver Data Tool

tasks good

ate your

e ant

er our ottom

elp

amiliar

ot

to rPivot

d the

ls

Trang 5

(SSDT), you can import the example workbook by using the Import from PowerPivot template in Visual Studio 2010 The basic DAX concepts and formulas described here work the same for tabular model projects as they do in PowerPivot Only the authoring environment user interface is different In SSDT, you can test your new formulas by using the Analyze in Excel feature

Let’s Begin!

We will frame DAX around three very important fundamental concepts: Syntax, Functions, and Context Of course,

there are other important concepts in DAX, but understanding these three concepts will provide the best foundation

on which to build your DAX skills

Syntax

Before you create your own formulas, let’s take a look at DAX formula syntax Syntax includes the various elements that make up a formula, or more simply, how the formula is written For example, let’s look at a simple DAX formula used to create new data (values) for each row in a calculated column, named Margin, in a FactSales table: (formula text colors are for illustrative purposes only)

This formula’s syntax includes the following elements:

A The equals sign operator (=) indicates the beginning of the formula, and when this formula is calculated it will return a result or value All formulas that calculate a value will begin with an equals sign

B The referenced column [SalesAmount] contains the values we want to subtract from A column reference in a formula is always surrounded by brackets [] Unlike Excel formulas which reference a cell, a DAX formula always references a column

C The subtraction (-) mathematical operator

D The referenced column [TotalCost] contains the values we want to subtract from values in the [SalesAmount] column

When trying to understand how to read a DAX formula, it is often helpful to break down each of the elements into a language you think and speak every day For example, you can read this formula as:

In the FactSales table, for each row in the Margin calculated column, calculate (=) a value by subtracting (-) values in the [TotalCost] column from values in the [SalesAmount] column

Trang 6

Let’s take a

This formu

A Th

fo

B Th

re

C Th

fu

D Pa

pa

E Th

F Th

kn

You can rea

For the me

FactSales ta

When plac

by each ce

Notice ther

column In

complex ca

functions la

Unlike the

in which th

preceded b

formula Th

practice to

Note:

If the name

in single qu

outside the

a look at anoth

la includes the

he measure na

ollowed by a co

he equals sign

eturn a result

he function SU

unctions later

arenthesis () s

asses a value to

he referenced t

he referenced c

nows on which

ad this formula

easure named S

able

ed into the Val

ll in the PivotTa

re are a few thi

particular, we

alculations and

ater

Margin calcula

he column belo

by the table na

his can make lo

always include

e of a table con

uotation marks

e ANSI alphanu

er type of form

following synt

me Sum of S

olon, followed b operator (=) in

UM adds up all o surround one o

o a function

table FactSal

column [Sale

column to agg

a as:

Sum of Sales Am

ues drop zone able, for examp

ings different a

introduced a fu

manipulations

ated column ea ngs This is kno

me Columns r ong formulas th

e the table nam

ntains spaces, r

s You must also umeric characte

mula, one that is

tax elements:

Sales Amou

by the calculati ndicates the be

of the numbers

or more argum

les

esAmount] in gregate a SUM

mount, calculat

in a PivotTable ple, Cell Phones

about this form

unction, SUM F

s with numbers

rlier, you see th

own as a fully q

eferenced in th hat reference m

me in your meas

reserved keywo

o enclose table

er range, regard

s used in a mea

unt Formulas

on formula

ginning of the

s in the [SalesA ents All functio

n the FactSales

te (=) the SUM

e Field List, this

s in the USA

mula compared Functions are p

s, dates, time, te

he column [Sal

qualified colum

he same table d many columns s sure formulas,

ords, or disallow

e names in quo dless of whethe

asure:

for measures c calculation for Amount] column ons require at

s table With th

M of values in th

s measure calcu

to the formula pre-written form ext, and more

esAmount] wa

mn name in that

do not require shorter and eas even when in t

wed characters, otation marks if

er your locale s

can include the rmula When ca

n You will learn least one argum

is argument, th

he [SalesAmoun ulates and retu

we used for th mulas that mak You will learn

s preceded by

t it includes the the table name sier to read Ho the same table

, you must enc

f the name con supports the ch

measure name alculated, it will

n more about ment An argum

he SUM functio

nt] column in t rns values defi

he Margin calcu

ke it easier to d more about

the table FactS

e column name

e be included in owever, it is goo

lose the table n tains any chara haracter set or

e,

ment

on

he ned

ulated

o

Sales

e

n the

od

name acters not

Trang 7

It is very important your formulas have the correct syntax In most cases, if the syntax is not correct, a syntax error will

be returned In other cases, the syntax may be correct, but the values returned might not be what you are expecting PowerPivot (and SQL Server Data Tools) includes IntelliSense; a feature used to create syntactically correct formulas by helping you select the correct elements

Let’s create a simple formula This task will help you further understand formula syntax and how the IntelliSense feature in the formula bar can help you

Task: Create a simple formula for a calculated column

1 If you are not already in the PowerPivot window, in Excel, on the PowerPivot ribbon, click PowerPivot

Window

2 In the PowerPivot window, click the FactSales table (tab)

3 Scroll to the right-most column, and then in the column header, click Add Column

4 Click in the formula bar along the top of the model designer window

Your cursor now appears in the formula bar The formula bar is where you can type a formula for a

calculated column or a measure

Let’s take a moment to look at the three buttons to the left of the formula bar

When the cursor is active in the formula bar, those three buttons become active The leftmost button, the X,

is simply a cancel button Go ahead and click it Your cursor no longer appears in the formula bar, and the cancel button and checkmark button no longer appear Go ahead and click in the formula bar again The cancel button and the checkmark button now reappear This means you are ready to start entering a

formula

Trang 8

co

C

Fu

fo

ca

5 In

w

Be

co

ca

Yo

6 Ty

7 N

If

ca

Af

bo

th

8 Ri

That’s it! Yo

formula ca

[SalesQuan

in DAX; row

Tip:

Something

arguments

be a text va

formula to

2, DAX read

result is of

based on t

scope of th

Books Onli

Let’s try an

much if you

several elem

Task: Crea

he checkmark b

ome back to it

lick the Fx butt

unction dialog

ormula when w

alculated colum

n the formula b

with all of the co

ecause calculat

olumn name w

an also scroll to

our cursor is no

ype a space, an

ow, type anoth

you get an err

alculated colum

fter you press E

ottom of the P

hree million row

ight click the co

ou just created

lculates a value

ntity] column N

w context You w

g really importa

you are using

alue of “12” Th

read: Calculate

ds this formula

course “3”, a n

he data type o

his Quick Start

ne

nother This tim

u don’t fully un

ments togethe

ate a measure

button is the ch

in a little bit

ton You’ll see t box is the easie

e create a mea

mn formula Go

ar, type an equ olumns in the F

ted columns ar ith the table na

o the column n

ow active to the

nd then type a her opening bra

or, look carefu

mn described ea

Enter to compl owerPivot wind

ws

olumn header

a simple yet v

e by subtracting Notice how we will learn more

ant to understa For example, i his is because t

e a result by tak

a as: Calculate a numeric value D

f columns used

To learn more

e, you will crea nderstand the f

r in correct syn

formula

heck formula b

that a new dial est way to get asure a little lat ahead and clo

uals sign =, the FactSales table

e always create ame Go ahead ame you want,

e right of [Sale

subtraction op acket [ This ti

lly at your synt arlier

ete the formula dow It goes qu and rename th

very powerful D

g the value in t

just said “For e

e about row con

nd when typing

if you were to t

he ampersand king the value

a result by takin DAX calculates

d in the argume about data typ

ate a measure b formula The im ntax

button It doesn

og box appear started enterin

er, but for now ose the Insert F

n type an open This is IntelliSe

ed in the active and scroll dow , and then pres

esQuantity]

erator - (a min

me, select the tax If necessary

a, the word Ca

uickly, even tho

e column, Net

DAX formula Fo the [ReturnQua

each row” This

ntext later

g an operator i type the follow (&) operator is

1 as text and a

ng the numeric resultant value ent Data types pes and operat

by typing the fo mportant thing

n’t do much un

rs; the Insert Fu

ng a DAX formu

w, you do not n unction dialog

ning bracket [ ense in action

e table you are

wn and then do

ss Tab

nus sign), and t

[ReturnQuant

y, compare it to

lculating appe

ough you just c

tSales

or each row in t

antity] column

is a glimpse of

into a DAX form wing formula, =

s for text conca

dd value 2 as t

c value 1 and ad

es depending o

s in DAX are ve tors in DAX form

ormula and by here is to learn

til you’ve enter

unction dialog b ula We’ll add a eed to add a fu box

You’ll see a sm

in, there is no

ouble-click [Sal

then type anoth

tity] column, an

o the formula in

ears in the statu alculated new

the FactSales ta from the value

f another very

mula is the dat

1 & 2, the valu atenation DAX text Now, if yo dding the num

on the operato

ry important, b mulas, see the

using IntelliSe

n how to create

red a formula W

box The Insert

a function to a unction to your mall window ap

need to preced

lesQuantity] Y

her space

nd then press E

n the Margin

us bar along th values for mor

able, the NetSa

in the important conc

a type in the

ue returned wo interprets this

u were to type meric value 2 Th

r in the formula but outside the

DAX Reference

nse Don’t wor

e a formula usin

We’ll

r ppears

de the You

Enter

he

e than

ales cept

ould = 1 +

he

a, not

e in

ry too

ng

Trang 9

1 In the FactSales table, click in any empty cell in the Calculation Area (also known as the measure grid in the

model designer) This is the area of empty cells just below a table in the PowerPivot window

2 In the formula bar, type the name Previous Quarter Sales:

3 Type an equals sign = to begin the calculation formula

4 Type the first few letters CAL, and then double-click the function you want to use In this formula, you want

to use the CALCULATE function

5 Type an opening parenthesis ( to begin the arguments to be passed to the CALCULATE function

Notice after typing the opening parenthesis, IntelliSense shows you the arguments required for the

CALCULATE function You will learn about arguments in a little bit

6 Type the first few letters of the FactSales table, and then in the dropdown list, double-click FactSales[Sales]

7 Type a comma (,) to specify the first filter, then type, PRE, and then double-click the PREVIOUSQUARTER

function

After selecting the PREVIOUSQUARTER function, another opening parenthesis appears, indicating another argument is required; this time, for the PREVIOUSQUARTER function

8 Type the first few letters Dim, and then double-click DimDate[DateKey]

9 Close both the argument being passed to the PREVIOUSQUARTER function and the CALCULATE function by typing two closing parentheses ))

Your formula should now look like this:

Previous Quarter Sales:=CALCULATE(FactSales[Sales],

PREVIOUSQUARTER(DimDate[DateKey]))

Trang 10

10 C

el

You did it!

the total sa

You were ju

Notice the

can contain

such a form

In this form

an argume

Finally, you

models and

function is

one

Note:

Typically, in

using the M

the DimDa

Tip:

You may b

have to’ A

model nee

measure yo

functions t

the AutoSu

Extra Cred

1 In the Fa

whole colu

2 On the H

3 Click the

you can us

Immediate

lick the check f

ement of the s

You just create

ales for the pre

ust introduced

PREVIOUSQUA

n up to 64 nest

mula would be

mula, you also u

ent, which is act

u used the CALC

d create more c

outside the sco

n order to use T

Mark as Date Ta

te table is selec

e asking: ‘Wha

nd, that is exac

ds to filter and

ou saw earlier i

hat aggregate

um feature

dit Task: Create

actSales table,

mn

Home tab, on t

e down arrow n

e, too)

ly, a new meas

formula button syntax

ed a measure u vious quarter, d

to several imp ARTER function ted functions I very difficult to

used filters Filt tually another f

CULATE functio complex formu ope of this Qui

Time Intelligen able dialog box cted as the uni

t is the simples ctly what you ca calculate on a

s used to add values as well

e a measure fo

scroll to the Re

the ribbon, click

next to AutoSu

sure is created w

n on the formul

using DAX, and depending on

portant aspects

n is nested as a

t is unlikely a fo

o create and de

ers narrow dow function You w

on This is one ulas, you will lik ickStart, but as

nce functions in

x In the Conto que date colum

st DAX formula

an do by using ggregated dat

up all the num You can autom

ormula by usin eturnQuantity

k the Measure

m, and then cl

with the name

a bar to validat

not an easy on the filters appl

of DAX formu

n argument pa ormula would e ebug, and it pro

wn what will be will learn more

of the most po kely use this fun your knowledg

n DAX formulas

so DAX Formu

mn

a I can create?’

g a standard ag

a For example bers in a partic matically create

ng the AutoSu

y column, and t

es button

ick Average (n

Average of

te the formula

ne at that Wha ied in a PivotTa

las First, this fo assed to the CA ever contain so obably wouldn

e calculated In about filters lat

owerful function nction many tim

ge of DAX grow

s, you must spe

la Samples.xlsx

Well, the answ gregation func , the SUM func cular column D

e formulas usin

um feature

then click on th

notice the other

f ReturnQu

If you get an e

at this formula able or PivotCh

ormula include ALCULATE funct

o many nested n’t be very fast e

this case, you ter

ns in DAX As y mes Discussing

ws, pay special

ecify a unique d

x workbook, the

wer to that is ‘th ction in a meas ction in the Sum DAX includes se

g standard agg

he column head

r standard agg

uantity: foll

error, verify eac

will do is calcu hart

d two function tion DAX form functions In fa either

selected one fi

you author data

g the CALCULA attention to th

date column by

e DateKey colu

he formula you ure Almost an

m of Sales Amo everal other gregations by u

der to select th

regation functi owed by the

ch late

s mulas act, lter as

a ATE his

y umn in

don’t

y data ount using

e

ions

Ngày đăng: 20/10/2014, 14:38

TỪ KHÓA LIÊN QUAN

w