Tải bản đầy đủ - 0 (trang)
Chapter 12. Grouping, Sorting, and Aggregating Data, Working with Scope

Chapter 12. Grouping, Sorting, and Aggregating Data, Working with Scope

Tải bản đầy đủ - 0trang

GroupingDataonaReport

Groupingallowsyoutoaggregateitemswithinagroupand,in

turn,togeneratereportswithcomplexformatting.Chapter8,

"Expressions,"coveredasetofaggregationfunctions.

Aggregationfunctionshelpgroupingscenariosbyproviding

totalsforgroupsandsubtotalsforsubgroups.Therelationship

betweenanaggregationfunctionandgroupiscontrolledby

scope.Thisrelationshipbecomesusefulwhen,forexample,a

userneedstoseewhatpercentageofatotalaparticularline

itemis.

Intheexamplesfrompreviouschapters,youhaveseen

summarizationsthatcanbedoneindataregions,suchasthe

Table,Matrix,Chart,andListdataregions.

MostscenariosemploygroupinginSSRStoaggregatedataand

generatesummaryinformation.Conceptsapplicableto

aggregationinSSRSareverysimilartothoseapplicabletothe

GROUPBYexpressioninSQL.However,unlikeaquery,which

allowsforverylimitedformatting,SSRSispracticallyunlimited

initsformattingcapabilities.

Asinmanycasesinsoftwaredevelopment,choosinga

particularapproachisbasedonseveralkeyfactors:

performance,scalability,elegance,anddevelopmenttime.This

isa"magic"formula.Thecomplexpartofthisistofindthebest

balancethatcansolvethis"magic."Thebestsolutionisto

experimentwithvariousapproachesandfindthebestfora

particularapplication.

Inalmostallcases,usingSQLforgroupingprovidesthebest

performance.However,astaticSQLstatementisnotvery

flexible.

TheSQLstatementmightbetoocomplex,loseitselegance,



and,especially,notproviderequiredformatting.Itmightbe

hardforadeveloper,whojuststartedworkingonanewly

developedreportingsystem,todeterminewhatacomplex

queryisdoingandwhyitisnotproducingthecorrectresult.

Thefollowingaresometipstohelpstrikeabalancebetween

SSRS'abilitytogroupandSQL:

Ideally,usesinglequerywithGROUPBY

Usequerygrouping(GROUPBY)withWHEREandHAVINGclausesif

itallowsyoutoreducetheamountofdatareceivedby

SSRS.

Donotformatorconvertdatainaquery,unlessneededfor

>GROUPBY.

Forexample,thefollowingquerytoretrieveasummaryofall

lineitemsforeachorderwiththeresultdisplayedinaTable

reportitemwillexecuteseveraltimesfasterthanusingaTable

reportitemtoaccomplishthesamegrouping.



[Viewfullwidth]



SELECTSales.SalesOrderHeader.SalesOrderNumber,SUM(Sales.S

ASSumOfDetails,SUM(Sales.SalesOrderHeader.SubTotal)ASOr

FROMSales.SalesOrderDetailINNERJOIN

Sales.SalesOrderHeaderONSales.SalesOrderDetail.SalesOr

.SalesOrderHeader.SalesOrderID

GROUPBYSales.SalesOrderHeader.SalesOrderNumber



TheGroupingandSortingPropertiesdialogboxprovidesan

interfacetoeditgroupsforMatrix,Table,List,andChart.



SeeFigure12.1toviewtheGroupingandSortingProperties

dialogboxforaTableGroup.



Figure12.1.GroupingandSortingProperties

dialogbox.



TheGroupingandSortingPropertiesdialogboxwillvaryslightly

incheckboxesatthebottom,dependingonthereportitem.For

example,ListonlyhasPageBreakatStartandPageBreakat

Endcheckboxes.

Thefollowingareprocedurestodisplaygroupingproperties:

ListRight-clickonalist,selectPropertiesfromtheshortcut



menu,andclicktheEditDetailsGroupbutton.

TableDetailRight-clickthedetailhandlerandselectEdit

Groupfromtheshortcutmenu.Thisgroupisnotvery

frequentlyusedasitonlyallowsyoutogroupdetailsand

doesnotprovidefunctionalitytocalculatesubtotals.

TableGroupOnanexistinggroup,Right-clickagroup

headerorfooterhandlerandselectEditGroupfromthe

shortcutmenu.

Thisisafrequentlyusedgroupandprovidesfunctionalityto

calculatesubtotalsandpaginationfunctionalityforagroup.

MatrixRight-clickaroworcolumngroupandselectEdit

Groupfromtheshortcutmenu.

ChartRight-clickonachart,selectPropertiesfromthe

shortcutmenu,clickontheDatatab,andselectEditon

eithertheSeriesorCategorygroups.

Thenumberofavailablegroupingpropertiesvaries,butName,

GrouponExpression(allowsformultipleexpressions),DocumentMap

Label(orsimplylabelinthecaseofaChartitem),andParent

Grouparealwaysavailable.TheRDLthatdescribesgroupingisas

follows:







=Fields!SalesOrderNumber.Value










Sorting,IncludingInteractiveUserSorting

InSSRS2005,threeoptionsareavailabletosortresultsona

report:

Makethedatasource(database)sortdataondataretrieval

byusinganORDERBYclause.

MakeSSRSsortdataduringreportgeneration.SSRSsorts

itemsthathavetheSortingpropertydefined.

Usethenew,interactivesortfunctionalityforHTMLrenderedreportsonly.ThisfunctionalitymakesSSRS

regenerateareportwithanewdirection:ascendingor

descending.

TheRDLthatdescribessortingisasfollows:





=Fields!Name.Value

Ascending











InteractiveSortingNEWin2005

SSRS2005addsanew,interactivesortactionthatallowsusers

tosortanHTML-renderedreport.

TheRDLthatdescribesinteractivesortingisasfollows:



=Fields!Name.Value





Adevelopercansetupthistypeofsortingthoughatextbox's

propertyUserSortorthroughtheInteractiveSorttabofatext

box'spropertysheet(seeFigure12.2).



Figure12.2.Interactivesorting.



Todeterminetheproperpositionofaninteractivesorting

control,visualizetheoutputanddecidewhatlocationmakes

sensefortheinteractiontooccur.Forexample,tosortvalues

withinagroup,acellinagroupheadershouldcontainan

interactivesortcontrol.

Thefollowingarethecomponentsofaninteractivesort:

Sortexpression(required)Normally,isacolumn

expressionforthecolumntobesorted.Forexample,ifthe

designerneedstosortacolumnthatcontainsthe

expression=Fields!FirstName.Value,thesameexpressionis

usedforsorting.Inafewcases,thedesignermightchoose

tousedifferentexpressionsforsorting;forexample,the

designermightdecidetouse=Fields!UserId.ValueifUserIdis

sequencedinthesamesortorderasFirstName.



Indataregionorgroupingtosortcurrentscope

Enablessortingontherepeatedrowsinthedataregionthat

containsthesortitem.Thescopemustbethecurrent

scope,apeerscopethatisadataregion,oranancestor

scope.TheChooseDataRegionorGroupingoptionallows

youtoselectaspecificdataregionorgroup(forexample,if

adeveloperwantsthesorttoaffectadditionaldataregions

ordataregionsotherthantheonethatcontainsthe

sortableitem).

EvaluatesortexpressioninthisscopeSpecifieswhich

dataregionsorgroupsaresorted.Settingtheseoptionsis

usefulifyouaretargetingaspecificdataregionandwantto

furtherspecifywheresortingoccurswithinthatdataregion.

DetailscopeSortsonlytherepeatedrowsoftheselected

dataregion.

DataregionorgroupingSelectsaspecificdataregionor

grouponwhichtosort.

Thereisnothingmagicalaboutinteractivesortingbehindthe

scenes.Ifyoulookattherenderedreport'ssource,youwill

noticethefollowingpiecesofthepuzzlewereaddedtoyour

fieldtobesorted:



[Viewfullwidth]




,'18_A');">




ImageNameisinitiallyunsorted.gifandchangestosortAsc.gifor

sortDesc.gif,dependingonthedirectionofthesort.Thisis



internalfunctionalitytoSSRSandyoudonotwanttomesswith

it.Itrevealsthatthe"magic"issimplyscripting.Youcan

furtherexplorethisfunctionalitybyaddingmoreinteractivesort

fieldsandobservingchangesinrenderedHTMLandthereport's

URL.







DataSourceSorting

AdesignercanusetheORDERBYclauseinaquery.Inthiscase,

thedatabaseperformssorting.Especiallyincasesinwhichthe

amountofdataislarge,thisprovidesthebestperformance.In

thiscase,adeveloperneedstoconsiderperformance

implicationsforthedatabaseserver.Inaddition,becausethe

queryapproachhasascopeofanentiredataset,itmightnot

provideneededfine-tuningfordatasorting.

Whennecessary,adesignercanparameterizedatasource

sortingbyusingthefollowingexpressionusedasthequeryina

dataset:="SELECT{fields}FROM{table}ORDERBY"&

Parameters!MySort.Value.

ParameterMySortshouldcontainavalidlistofdatabasefieldsor

numberscorrespondingtothefieldstouseinORDERBY.

Forexample,toretrievealistofemployees,usethefollowing

expression:



="SELECTFirstName,LastName,TitleFROMEmployeeORDERBY"&



,Inthise,xample,MySortcouldbesettoanonqueriedparameter

withthevaluesFirstNameandLastNameorvalues1and2.Formore

detailsaboutparameters,includinginformationonhowtopass

aparametervaluetoareport,refertoChapter10,"Report

Parameters."

Fordynamicqueryexpressions,developersneedtomakesure

thatParameters!MySort.Valueproperlycorrespondstoadatabase

fieldorfields.Inaddition,adynamicqueryexpressionhasto

returnavalidquery.Eachproperlyplacedspaceiscrucial,such

asthespacebetweenORDERBYandaparameter.



QuerydesignhastofollowbestpracticestoavoidSQLinjection.

HereisagoodarticleonavoidingSQLinjectionattacks:

http://msdn.microsoft.com/msdnmag/issues/04/09/SQLInjection/







Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 12. Grouping, Sorting, and Aggregating Data, Working with Scope

Tải bản đầy đủ ngay(0 tr)

×