real sql queries

197

Upload: others

Post on 21-Oct-2021

41 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: REAL SQL QUERIES
Page 2: REAL SQL QUERIES

REALSQLQUERIES50CHALLENGES

BRIANCOHEN

NEILPEPI

NEERJAMISHRA

Page 3: REAL SQL QUERIES

RealSQLQueries:50ChallengesByBrianCohen,NeilPepi,andNeerjaMishra

©2015BrianCohen,NeilPepi,andNeerjaMishra.

Allrightsreserved.Nopartofthisbookmaybereproducedortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,orotherwise,withoutpriorwrittenpermissionoftheauthorsattheaddressbelow.

BrianCohen31748BlythewoodWayWesleyChapel,FL33543

Microsoft,Excel,andSQLServerareeitherregisteredtrademarksortrademarksofMicrosoftCorporationintheUnitedStatesand/orothercountries.Allothertrademarksarethepropertyoftheirrespectiveowners.Whentrademarkdesignationsappearinthisbook,andtheauthorswereawareofatrademarkclaim,thedesignationshavebeenprintedininitialcapitalletters.

Whileeveryprecautionhasbeentakeninthepreparationofthisbook,theauthorsassumenoresponsibilityforerrorsoromissions,orfordamagesresultingfromtheuseorinformationcontainedherein.

CopyEditor:HaleyDeLeon

Additionalcontentavailableonlineathttp://realsqlqueries.com

Page 4: REAL SQL QUERIES
Page 5: REAL SQL QUERIES

ABOUTTHEAUTHORS

Page 6: REAL SQL QUERIES

BRIANCOHENBrianCohenisSeniorDatabaseMarketingAnalystatBiskEducationwhereheanalyzestheeffectivenessofmarketinginitiatives.BrianearnedhisBachelorofArtsinEconomicsfromUniversityofSouthFloridain1997.HeholdsaMasterCertificateinInternetMarketingfromUniversityofSanFranciscoandiscurrentlyenrolledwithVillanovaUniversity,seekingaMasterCertificateinBusinessIntelligence.MoreaboutBrianCohenathttp://bricohen.comManythankstoBrian’swifeRenéforherencouragementthroughouttheprocessofcreatingthebook.BrianalsothankshiscolleaguesatBiskEducation.Brianisfortunatetoworkalongsidesomanyexpertswhoshareknowledgegenerously.

Page 7: REAL SQL QUERIES

NEILPEPINeillearnedalotofwhatheknowstodayatBiskEducation,whereheiscurrentlyaDatabaseReportingAnalyst.Biskcreatedanenvironmentthatholdspractical,on-the-joblearningasapriority.Hewouldberemissifhedidn’tthanktheownersofBiskEducationandallofthetalentedpeoplethatworkthere.NeilearnedhisBachelorofScienceinAccountingfromtheUniversityofSouthFlorida.Hecanbecontactedatneilpepi1@gmail.com.

Page 8: REAL SQL QUERIES

NEERJAMISHRANeerjaMishraisaSQLDevelopercurrentlyworkingwithCitibankinTampaFlorida.ShegraduatedfromUniversityofDelhi,IndiawithaBachelorinScienceandsheearnedherMaster’sinEngineeringfromSouthDakotaStateUniversity.Besidesherwork,sheenjoysmusic,travelling,watchingdocumentariesandreading.NeerjaMishracanbecontactedatnes1711@hotmail.com.

Page 9: REAL SQL QUERIES

TABLEOFCONTENTSABOUTTHEAUTHORSBRIANCOHEN

NEILPEPI

NEERJAMISHRA

INTRODUCTIONTHECHALLENGES

THESOLUTIONS

WHAT’SNEEDED

ORGANIZATION

EXPLORINGANEWDATABASECHALLENGEQUESTIONSCHALLENGEQUESTION1:YEAROVERYEARCOMPARISONS

CHALLENGEQUESTION2:THE2/22PROMOTION

CHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

CHALLENGEQUESTION4:UPSELLTUESDAYSCHALLENGEQUESTION5:EXPIREDCREDITCARDS

CHALLENGEQUESTION6:PRINTCATALOG

CHALLENGEQUESTION7:SPECIALTEAMCHALLENGEQUESTION8:KNAPSACKPROBLEM

CHALLENGEQUESTION9:PRODUCTCOMBINATIONS

CHALLENGEQUESTION10:MEDIANREVENUE

CHALLENGEQUESTION11:NEEDYACCOUNTANT

CHALLENGEQUESTION12:PRODUCTINVENTORYUPDATES

CHALLENGEQUESTION13:VACATIONHOURS

CHALLENGEQUESTION14:PURCHASING

CHALLENGEQUESTION15:INTERPRETATIONNEEDED

CHALLENGEQUESTION16:ONLINE/OFFLINE

CHALLENGEQUESTION17:LONGTIMENOSALE

CHALLENGEQUESTION18:COSTSVARY

Page 10: REAL SQL QUERIES

CHALLENGEQUESTION19:THERMOFORMTEMPERATURECHALLENGEQUESTION20:TORONTOCHALLENGEQUESTION21:MARKETINGEMPLOYEES

CHALLENGEQUESTION22:WHOLEFTTHATREVIEW?CHALLENGEQUESTION23:LABELMIX-UP

CHALLENGEQUESTION24:CLEARANCESALE

CHALLENGEQUESTION25:TOPTERRITORIESCHALLENGEQUESTION26:COMMISSIONPERCENTAGES

CHALLENGEQUESTION27:WORKORDERS

CHALLENGEQUESTION28:REVENUETRENDEDCHALLENGEQUESTION29:SEPARATION

CHALLENGEQUESTION30:SHIFTCOVERAGE

CHALLENGEQUESTION31:LABELSCHALLENGEQUESTION32:EMPLOYMENTSURVEY

CHALLENGEQUESTION33:AGEGROUPS

CHALLENGEQUESTION34:REVENUEBYSTATE

CHALLENGEQUESTION35:TWOFREEBIKES

CHALLENGEQUESTION36:VOLUMEDISCOUNTS

CHALLENGEQUESTION37:OVERPAYING

CHALLENGEQUESTION38:MARGINS

CHALLENGEQUESTION39:PERCENTTOQUOTA

CHALLENGEQUESTION40:REVENUERANGES

CHALLENGEQUESTION41:E-MAILMYSTERY

CHALLENGEQUESTION42:THEMENTORS

CHALLENGEQUESTION43:CALENDAROFWORKDAYS

CHALLENGEQUESTION44:ANNUALSALARYBYEMPLOYEE

CHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENT

CHALLENGEQUESTION46:HOLIDAYBONUS

CHALLENGEQUESTION47:COMPANYPICNIC

CHALLENGEQUESTION48:SALESQUOTACHANGES

CHALLENGEQUESTION49:SCRAPRATE

Page 11: REAL SQL QUERIES

CHALLENGEQUESTION50:REASONS

CHALLENGEQUESTION51:EXCESSINVENTORYCHALLENGEQUESTION52:PAYRATECHANGES

HINTSFORCHALLENGEQUESTIONSHINTSFORCHALLENGEQUESTION1:YEAROVERYEARCOMPARISONS

HINTSFORCHALLENGEQUESTION2:THE2/22PROMOTION

HINTSFORCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

HINTSFORCHALLENGEQUESTION4:UPSELLTUESDAYSHINTSFORCHALLENGEQUESTION5:EXPIREDCREDITCARDS

HINTSFORCHALLENGEQUESTION6:PRINTCATALOG

HINTSFORCHALLENGEQUESTION7:SPECIALTEAMHINTSFORCHALLENGEQUESTION8:KNAPSACKPROBLEM

HINTSFORCHALLENGEQUESTION9:PRODUCTCOMBINATIONS

HINTSFORCHALLENGEQUESTION10:MEDIANREVENUE

HINTSFORCHALLENGEQUESTION11:NEEDYACCOUNTANT

HINTSFORCHALLENGEQUESTION12:PRODUCTINVENTORYUPDATES

HINTSFORCHALLENGEQUESTION13:VACATIONHOURS

HINTSFORCHALLENGEQUESTION14:PURCHASING

HINTSFORCHALLENGEQUESTION15:INTERPRETATIONNEEDED

HINTSFORCHALLENGEQUESTION16:ONLINE/OFFLINE

HINTSFORCHALLENGEQUESTION17:LONGTIMENOSALE

HINTSFORCHALLENGEQUESTION18:COSTSVARY

HINTSFORCHALLENGEQUESTION19:THERMOFORMTEMPERATUREHINTSFORCHALLENGEQUESTION20:TORONTOHINTSFORCHALLENGEQUESTION21:MARKETINGEMPLOYEES

HINTSFORCHALLENGEQUESTION22:WHOLEFTTHATREVIEW?HINTSFORCHALLENGEQUESTION23:LABELMIX-UP

HINTSFORCHALLENGEQUESTION24:CLEARANCESALE

HINTSFORCHALLENGEQUESTION25:TOPTERRITORIESHINTSFORCHALLENGEQUESTION26:COMMISSIONPERCENTAGES

HINTSFORCHALLENGEQUESTION27:WORKORDERS

Page 12: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION28:REVENUETRENDEDHINTSFORCHALLENGEQUESTION29:SEPARATION

HINTSFORCHALLENGEQUESTION30:SHIFTCOVERAGE

HINTSFORCHALLENGEQUESTION31:LABELSHINTSFORCHALLENGEQUESTION32:EMPLOYMENTSURVEY

HINTSFORCHALLENGEQUESTION33:AGEGROUPS

HINTSFORCHALLENGEQUESTION34:REVENUEBYSTATE

HINTSFORCHALLENGEQUESTION35:TWOFREEBIKES

HINTSFORCHALLENGEQUESTION36:VOLUMEDISCOUNTS

HINTSFORCHALLENGEQUESTION37:OVERPAYING

HINTSFORCHALLENGEQUESTION38:MARGINS

HINTSFORCHALLENGEQUESTION39:PERCENTTOQUOTA

HINTSFORCHALLENGEQUESTION40:REVENUERANGES

HINTSFORCHALLENGEQUESTION41:E-MAILMYSTERY

HINTSFORCHALLENGEQUESTION42:THEMENTORS

HINTSFORCHALLENGEQUESTION43:CALENDAROFWORKDAYS

HINTSFORCHALLENGEQUESTION44:ANNUALSALARYBYEMPLOYEE

HINTSFORCHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENT

HINTSFORCHALLENGEQUESTION46:HOLIDAYBONUS

HINTSFORCHALLENGEQUESTION47:COMPANYPICNIC

HINTSFORCHALLENGEQUESTION48:SALESQUOTACHANGES

HINTSFORCHALLENGEQUESTION49:SCRAPRATE

HINTSFORCHALLENGEQUESTION50:REASONS

HINTSFORCHALLENGEQUESTION51:EXCESSINVENTORYHINTSFORCHALLENGEQUESTION52:PAYRATECHANGES

SOLUTIONSTOCHALLENGEQUESTIONSSOLUTIONTOCHALLENGEQUESTION1:YEAROVERYEARCOMPARISONS

SOLUTIONTOCHALLENGEQUESTION2:THE2/22PROMOTION

SOLUTION1TOCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

SOLUTION2TOCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

SOLUTIONTOCHALLENGEQUESTION4:UPSELLTUESDAYS

Page 13: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION5:EXPIREDCREDITCARDS

SOLUTIONTOCHALLENGEQUESTION6:PRINTCATALOG

SOLUTIONTOCHALLENGEQUESTIONS7:SPECIALTEAMSOLUTIONTOCHALLENGEQUESTION8:KNAPSACKPROBLEM

SOLUTIONTOCHALLENGEQUESTION9:PRODUCTCOMBINATIONS

SOLUTION1TOCHALLENGEQUESTION10:MEDIANREVENUE

SOLUTION2TOCHALLENGEQUESTION10:MEDIANREVENUE

SOLUTIONTOCHALLENGEQUESTION11:NEEDYACCOUNTANT

SOLUTIONTOCHALLENGEQUESTION12:PRODUCTINVENTORYUPDATES

SOLUTIONTOCHALLENGEQUESTION13:VACATIONHOURS

SOLUTIONTOCHALLENGEQUESTION14:PURCHASING

SOLUTIONTOCHALLENGEQUESTION15:INTERPRETATIONNEEDED

SOLUTIONTOCHALLENGEQUESTION16:ONLINE/OFFLINE

SOLUTIONTOCHALLENGEQUESTION17:LONGTIMENOSALE

SOLUTIONTOCHALLENGEQUESTION18:COSTSVARY

SOLUTIONTOCHALLENGEQUESTION19:THERMOFORMTEMPERATURESOLUTIONTOCHALLENGEQUESTION20:TOTONTOSOLUTIONTOCHALLENGEQUESTION21:MARKETINGEMPLOYEES

SOLUTIONTOCHALLENGEQUESTION22:WHOLEFTTHATREVIEW?SOLUTIONTOCHALLENGEQUESTION23:LABELMIX-UP

SOLUTIONTOCHALLENGEQUESTION24:CLEARANCESALE

SOLUTIONTOCHALLENGEQUESTION25:TOPTERRITORIESSOLUTIONTOCHALLENGEQUESTION26:COMMISSIONPERCENTAGES

SOLUTIONTOCHALLENGEQUESTION27:WORKORDERS

SOLUTIONTOCHALLENGEQUESTION28:REVENUETRENDEDSOLUTIONTOCHALLENGEQUESTION29:SEPARATION

SOLUTIONTOCHALLENGEQUESTION30:SHIFTCOVERAGE

SOLUTIONTOCHALLENGEQUESTION31:LABELSSOLUTIONTOCHALLENGEQUESTION32:EMPLOYMENTSURVEY

SOLUTIONTOCHALLENGEQUESTION33:AGEGROUPS

SOLUTIONTOCHALLENGEQUESTION34:REVENUEBYSTATE

Page 14: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION35:TWOFREEBIKES

SOLUTIONTOCHALLENGEQUESTION36:VOLUMEDISCOUNTS

SOLUTIONTOCHALLENGEQUESTION37:OVERPAYING

SOLUTIONTOCHALLENGEQUESTION38:MARGINS

SOLUTIONTOCHALLENGEQUESTION39:PERCENTTOQUOTA

SOLUTIONTOCHALLENGEQUESTION40:REVENUERANGES

SOLUTIONTOCHALLENGEQUESTION41:E-MAILMYSTERY

SOLUTIONTOCHALLENGEQUESTION42:THEMENTORS

SOLUTIONTOCHALLENGEQUESTION43:CALENDAROFWORKDAYS

SOLUTIONTOCHALLENGEQUESTION44:ANNUALSALARIESBYEMPLOYEE

SOLUTIONTOCHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENT

SOLUTIONTOCHALLENGEQUESTION46:HOLIDAYBONUS

SOLUTIONTOCHALLENGEQUESTION47:COMPANYPICNIC

SOLUTIONTOCHALLENGEQUESTION48:SALESQUOTACHANGES

SOLUTIONTOCHALLENGEQUESTION49:SCRAPRATE

SOLUTIONTOCHALLENGEQUESTION50:REASONS

SOLUTIONTOCHALLENGEQUESTION51:EXCESSINVENTORYSOLUTIONTOCHALLENGEQUESTION52:PAYRATECHANGES

Page 15: REAL SQL QUERIES

INTRODUCTION

We,theauthors,arepracticaldevelopers.Whileweareinterestedinconceptuallearning,wethinkrealproblemsolvingisking.Intextbooks,weskiptothepracticequeries.Atwork,wescourtheinternetforcodingtechniquestoanswerquestionsaboutourbusiness.We’remostexcitedbySQLqueriesthatgetthejobdone.With50challengequestions,thisbookenablesthepracticaldeveloper.Tomakethematerialmorerelatable,we’vedesignedthechallengeswithreportwritersandanalystsinmind.Andwe’vetailoredallchallengestoAdventureWorks2012,Microsoft’suniversally-accessiblesampledatabase,sothatyoucanbeginqueryingimmediately.

Page 16: REAL SQL QUERIES

THECHALLENGESThedifficultyofthechallengesthroughoutthebookismixed,sothematerialaccommodatesmanybackgrounds.Somequestionsaresimple,whileotherscallforstrategic,multi-stepsolutions.WeaimedtoincludeabroadgroupofSQLuserswithinouraudience.

Page 17: REAL SQL QUERIES

THESOLUTIONSWebelieveindependentreasoningisessential.Accordingly,solutionsareprovidedbutnotnecessarilydissected.Weempoweryoutothinkthroughourcodewithoutinterruptionornoise.Oursolutionsfavorhumanlogicandreadabilityoverperformance.Weworkedthroughtheproblemsinwaysthatwererationaltouswhilecarryingreasonableefficiency.Performancetuningiscertainlyworthy,butitscraftfallsoutsidethescopeofthisbook.Therearemanypossibleapproachestoanygivensolution,soyou’relikelytodiscoveralternateroutesthatfeelmoreappropriate.Likewise,numerouscodingstylesexistandourpreferencesmaynotlineupwithyours.WeencourageyoutorewritetheSQLasyouseefit.

Page 18: REAL SQL QUERIES

WHAT’SNEEDEDThebookisbestsupportedbySQLServer2012withAdventureWorks2012.TheExpressversionofSQLServer2012isfree,soyoushouldinstallthesoftwareifneeded.AdventureWorks2012isfreeaswell.Thefollowinglinksshouldassistyouwithdownloadsandinstallations:SQLServerExpress2012DownloadAventureWorks2012Download

Page 19: REAL SQL QUERIES

ORGANIZATIONThebookisdividedintotwoparts.InPartI,webeginwithadiscussionaboutnavigatingrelationshipsamongunfamiliartables.We’veoutlinedideastohelpyoupreparetherightroadmapfortherightproblem-solvingjourney.PartIcontinueswithlotsofvariedchallengequestionsforyoutry.InPartII,you’llfindhints,strategies,andsolutions.Weplacedthismaterialfarawayfromthechallengequestionsbydesign.Youwon’taccidentallybumpintounwantedanswerswhileyou’reworkingthroughquestions.Asmentionedearlier,weenableyoutothinkwithoutinterruption.We’vepreparedeachsolutionasadistinct.sqlfilefordownload.Feelfreetoretrievewhicheverfilesyoulikeathttp://realsqlqueries.com/

Page 20: REAL SQL QUERIES

EXPLORINGANEWDATABASE

Itisnotuncommonforareportwriteroranalysttobethrownintoanewdatabasewithlittletonoguidance,letaloneadatadictionary.Forexactlythesereasons,itcanbebeneficialtobeabletoinvestigateadatabaseyourselfbeforeaskingyourcoworkersunnecessaryquestions.Luckily,SQLServerhasalotofrobusttoolsbuilt-inforconductingsuchresearch.Forexample,let’ssayyouwanttofindacolumnsomewhereinthedatabase,butyou’renotsurewhattableitexistson.Thecodebelowcandoexactlythat;allyouhavetodoisreplacethedatabasenameandthecolumnnameyou’researchingfor.

USEDatabaseNameGO

—DROPTABLE#data

SELECTTableView=ISNULL(N2.Name,N3.Name),ObjectView=CASEWHENN2.NameISNOTNULLTHEN‘Table’ELSE‘View’END,ColName=N1.NameINTO#dataFROMsys.columnsN1LEFTJOINsys.tablesN2ONN1.object_id=N2.object_idLEFTJOINsys.viewsN3ONN1.object_id=N3.object_idWHEREN2.object_idISNOTNULLORN3.object_idISNOTNULLORDERBYTableView

SELECT*FROM#dataWHEREColNameLIKE‘%ColumnName%’

Now,let’ssayyou’vefoundthetableyouwanttouse,butyou’renotentirelysurehowit’sstructured.Forexample,howdoyoufindoutifacolumnisuniqueifthereisn’taprimarykeyconstraint?Thecodebelowcanshowyouanyvalueforthe

Page 21: REAL SQL QUERIES

fieldselectedthathasmorethan1row.Ifthisqueryreturnsnoresults,thefieldyou’vechosenisunique.

SELECTColumnNameFROMTableNameGROUPBYColumnNameHAVINGCOUNT(*)>1

Ifweaugmentthatcodeslightly,wecannowcheckforrelationships.ThefollowingqueryischeckingifanyvaluesexistforColumnName1thathavemultiplevaluesinColumnName2.SELECTColumnName1FROMTableNameGROUPBYColumnName1HAVINGCOUNT(DISTINCTColumnName2)>1Ifwethenruntheopposite,wecandeterminetherelationshipbetweenthesetwocolumns.

SELECTColumnName2FROMTableNameGROUPBYColumnName2HAVINGCOUNT(DISTINCTColumnName1)>1

Basedontheresults,thetablebelowcanshowyoutherelationshipbetweenColumnName1andColumnName2.

Page 22: REAL SQL QUERIES
Page 23: REAL SQL QUERIES

CHALLENGEQUESTIONS

CHALLENGEQUESTION1:YEAROVERYEARCOMPARISONSDifficulty:Intermediate

Anexecutiverequestsdataconcerningfiscalquartersalesbysalesperson.She’dliketoseecomparisonsfromthefiscalquartersof2008tothesamefiscalquartersof2007.Forexample,supposesalesforsalespersonXtotaled$1,000duringFiscalYear2008,FiscalQuarter2.IfsalesforsalespersonXtotaled$900inFiscalYear2007,FiscalQuarter2,thisreflectsabout11.1%growthbetweenthetwoperiodsforsalespersonX.Notes:

ForAdventureWorks,thefiscalyearspansJulythroughJuneTaxandfreightwillnotbeconsideredwithrevenueDatesarebasedonOrderDateDisregardonlineorders

Youroutputshouldincludethefollowingcolumns,correspondingtoallsalespeople:

LastNameSalesPersonIDFiscalyearFiscalquarterFiscalquartersalesSalesduringthesamefiscalquarterofthepreviousfiscalyearChangeinrevenuebetweenthetwoperiodsPercentchangeinrevenuebetweenthetwoperiods

Followingthesameexample,youroutputforonerowwouldappearasfollows:

Page 24: REAL SQL QUERIES

CHALLENGEQUESTION2:THE2/22PROMOTIONDifficulty:Intermediate

Amarketingmanagerdevisedthe“2/22”promotion,inwhichorderssubtotalingatleast$2,000shipfor$0.22.Thestrategyassumesthatfreightlosseswillbeoffsetbygainsfromhighervalueorders.Accordingtothemarketingmanager,ordersbetween$1,700and$2,000willlikelyboostto$2,000ascustomersfeelcompelledtotakeadvantageofbargainfreightpricing.Youareaskedtotestthe2/22promotionforhypotheticalprofitabilitybasedonthemarketingmanager’sassumptionaboutcustomerbehavior.ExamineordersshippedtoCaliforniaduringfiscalyear2008fornetgainsorlossesunderthepromotion.

PARTICreateatablethatincludesthefollowingcolumns:

SalesOrderIDShiptostate(California)OrderDateHistoricalordersubtotal(priortoanychangesasaresultofthepromotion)Historicalfreight(priortoanychangesasaresultofthepromotion)Potentialpromotionaleffect.Indicateoneofthreehypotheticalscenariosrelatedtotheorder:

Increaseorderto$2,000andpay$0.22freightNoorderchangeandpay$0.22freightNoorderchangeandpayhistoricalfreight

PotentialordergainPotentialfreightlossPotentialpromotionalnetgain/loss

Notes:ForAdventureWorks,thefiscalyearspansJulythroughJuneTaxshouldnotbeconsidered

PARTIIAggregatedatafromPartIbyPotentialPromotionalEffect.Includethefollowing:

PotentialPromotionalEffectPotentialordergainsPotentialfreightlossesOverallnetgain/loss

Page 25: REAL SQL QUERIES

CHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARKDifficulty:Intermediate

TenmilliondollarsofrevenueisacommonbenchmarkforAdventureWorks.Foreachfiscalyear(2007and2008),findthefirstdateswhenthecumulativerunningrevenuetotalhit$10million.Notes:

ForAdventureWorks,thefiscalyearspansJulythroughJuneDonotconsidertaxandfreightwithrevenue

Youroutputshouldincludethefollowingcolumns:Fiscalyear(2007or2008)Orderdateinwhich$10millionwasreachedorexceededOrdernumberwithinthefiscalyearinwhich$10millionwasreachedorexceeded.Note,thisisacountoforders.Forexample,ifthe$10milliongoalwasreachedonthe50thorder,thentheappropriatevaluetoreportis50.Runningtotalrevenueinwhich$10millionwasreachedorexceeded

Exampleoutput:

Page 26: REAL SQL QUERIES

CHALLENGEQUESTION4:UPSELLTUESDAYSDifficulty:Beginner

Tuesday’sare“upsell”daysforsalespeopleatAdventureWorks.ManagementwantstocomparesalesfromTuesdaytootherdaysoftheweektoseeiftheinitiativeisworking.Helpmonitortheupsellinitiativebycreatingaquerytocalculateaveragerevenueperorderbydayofweekin2008.Includethefollowingcolumnswithyouroutput:

DayofweekRevenueOrdersRevenueperorder

Notes:DatesbasedonOrderDateTaxandfreightshouldnotbeconsideredExcludeonlineorders

CHALLENGEQUESTION5:EXPIREDCREDITCARDSDifficulty:Intermediate

TheAccountingdepartmentfoundinstanceswhereexpiredcreditcardswereusedwithsalesorders.Youareaskedexamineallcreditcardsandreporttheextentofsuchactivity.

PARTIBasedoneachCreditCardID,findthefollowing:

CreditCardTypeExpirationDateLastorderdateNumberofsalesorderswithorderdatesearlierthanorequaltothecard’sexpirationdateNumberofsalesorderswithorderdateslaterthanthecard’sexpirationdate

Note:AdventureWorksstoresinformationaboutacreditcard’sexpirationyearandexpirationmonth.Expirationdatespertaintothelastdayofacard’sexpiration

Page 27: REAL SQL QUERIES

month.Forexample,iftheexpirationyearis2007andtheexpirationmonthis“4”,thecard’sexpirationdatewillbeApril30,2007.

PARTIIBasedonCreditCardType,summarizedatareturnedfromPartI.Youroutputshouldincludethefollowingcolumns:

CreditCardTypeNumberofsalesorderswithorderdatesearlierthanorequaltothecard’sexpirationdateNumberofsalesorderswithorderdateslaterthanthecard’sexpirationdate

Page 28: REAL SQL QUERIES

CHALLENGEQUESTION6:PRINTCATALOGDifficulty:Beginner

AdventureWorkswillfeatureoneproductforthecoverofitsprintcatalog.Helpselectalistofproductsforconsideration.Yourlistshouldcontainproductswhichmeetallofthefollowingconditions:

Finishedgoods(notproductsutilizedtomakeotherproducts)Listpriceatleast$1,500Atleast150ininventoryCurrentlyavailableforsale

Youroutputshouldcontainthefollowingcolumns:ProductIDProductNameColorListPriceInventoryquantity

Page 29: REAL SQL QUERIES

CHALLENGEQUESTION7:SPECIALTEAMDifficulty:Intermediate

AnAdventureWorksexecutiveasksforalistofallsalespeoplerepresentingtheNorthwest,Southwest,andCanadiansalesterritories,alongwiththeir2008revenue.Youaskaboutthepurposeoftheinformation.“I’massemblinga‘specialteam,’theexecutiveresponds.“I’lltellyoumoresoon.”Createalistofsalespeoplewithrevenueasrequested.Donotconsidertaxandfreight.

Page 30: REAL SQL QUERIES

CHALLENGEQUESTION8:KNAPSACKPROBLEMDifficulty:Advanced

Thefollowingday,aftercompletingthepreviouschallenge,theexecutiveapproachesyouagain.“I’mstartinganewcompany,”hesays.“That’swhyIaskedfortheinformationyesterday.Ineedyoutorecommendcandidatesforrecruitment.IwantonesalespersonfromtheNorthwestterritory,onefromtheSouthwestterritory,andonefromtheCanadianterritory.Whichthree-personcombinationofsalespeopleresultsinthehighestrevenue?Baseyourcalculationsonthe2008revenueyoupreviouslyfound.Iwantthebestteam,butwecannotexceedthesalaryconstraints.Mysalarybudgetforthecombinedrostermustbelessthan$210,000.”Belowarethesalariesyoucanoffertoeachsalesperson,asprovidedbytheexecutive:

Pak:$79,500Vargas:$60,000Campbell:$59,500Mensa-Annan:$56,000Ito:$68,000Michel:$80,000

Basedon2008revenue,findthemostvaluablecombinationofsalespeoplewithinthesalaryconstraint.Youroutputshouldincludeasinglerowwiththefollowingcolumns:

SumofsalariesofyourthreepersonteamSumofrevenuefromyourthreepersonteamTerritoryofthefirstsalespersonLastnameoffirstsalespersonRevenueoffirstsalespersonSalaryoffirstsalespersonTerritoryofthesecondsalespersonLastnameofsecondsalespersonRevenueofsecondsalespersonSalaryofsecondsalespersonTerritoryofthethirdsalespersonLastnameofthirdsalespersonRevenueofthirdsalespersonSalaryofthirdsalesperson

Exampleoutput:

Page 31: REAL SQL QUERIES
Page 32: REAL SQL QUERIES

CHALLENGEQUESTION9:PRODUCTCOMBINATIONSDifficulty:Advanced

Theexecutivemanagementteamwantstoanalyzethebuyingbehaviorofcustomers.

PARTIProvidethefollowingcalculations:

PercentageofsalesorderscontainingatleastonebikeandatleastoneaccessoryitemPercentageofsalesorderscontainingatleastonebikeandatleasttwodifferentclothingproducts

PARTIICountsalesordersbyproducttype.Forexample,if500salesordersincludedtheproducttypesBikesandClothing,withnoaccessoriesandcomponentspurchased,thatoutputrowwouldappearasfollows:

PARTIIICountcustomersbyproductline.Forexample,if100customerspurchasedproductsfromproductlinesMandT,butnotSandR,thatoutputrowwouldappearasfollows:

Page 33: REAL SQL QUERIES

CHALLENGEQUESTION10:MEDIANREVENUEDifficulty:Intermediate

AnanalystnotifiedtheVicePresidentofSalesthataveragescanbeskewedbyoutliers.Inresponse,heaskstoseemedianrevenueinadditiontoaveragerevenue.Healsoasksyoutoaddminimumandmaximumrevenuetoyourreport.Writeaqueryofsalesbyyearthatincludesthefollowingcolumns:

OrderyearMinimumsaleMaximumsaleAveragesaleMediansale

Notes:YearsbasedonOrderDateTaxandfreightshouldnotbeconsideredwithrevenue

Page 34: REAL SQL QUERIES

CHALLENGEQUESTION11:NEEDYACCOUNTANTDifficulty:Beginner

AnaccountantneedstoaddassumptionsaboutsalestaxratestohisExcelworksheet.Heasksyoutoprovideonesalestaxrate,conservatively,foreachofthecountriesinwhichtaxratesareknown.Tofulfillhisrequest,reportthemaximumsalestaxrateofeachcountry.

Page 35: REAL SQL QUERIES

CHALLENGEQUESTION12:PRODUCTINVENTORYUPDATESDifficulty:Advanced

YouareaskedtoprovidefrequentupdatesabouttheAdventureWorksproductinventory.Createaviewthatincludesthefollowing:

NumberofdistinctproductsbyLocationIDQuantityofproductsbyLocationIDArollupwithtotalnumberofdistinctproductsthroughoutallLocationIDsArollupwithtotalquantityofproductsthroughoutallLocationIDs

Page 36: REAL SQL QUERIES

CHALLENGEQUESTION13:VACATIONHOURSDifficulty:Intermediate

HumanResourcesisreevaluatingapolicyaboutmaximumallowablevacationrolloverhours.Youareaskedtohelpbyidentifyingtheemployeeorgroupofemployeeswiththegreatestnumberofvacationhours.SincemanyHumanResourcesfilesareindexedbyNationalIDNumber,pleaseincludethelastfourdigitswithyouroutput.Inall,youroutputshouldcontainthefollowinginformation:

LastfourdigitsofNationalIDNumberFirstNameLastNameJobTitleNumberofvacationhours

Page 37: REAL SQL QUERIES

CHALLENGEQUESTION14:PURCHASINGDifficulty:Intermediate

ForeachproductorderedbythePurchasingDepartmentin2007,indicatethequantityorderedbyorderdate.Inall,includethefollowingcolumnswithyouroutput:

ProductIDProductnameOrderDateQuantityordered

Arrangedataindescendingorderbyquantityordered.

Page 38: REAL SQL QUERIES

CHALLENGEQUESTION15:INTERPRETATIONNEEDEDDifficulty:Intermediate

TheAdventureWorksMarketingdepartmentutilizescontractorstoreviewforeignlanguageproductdescriptions.Tohelpthecontractors,youareaskedtopreparealistofallproductdescriptionswritteninlanguagesotherthanEnglish.Youroutputshouldcontainthefollowingcolumns:

ProductModelIDNameofproductmodelProductdescriptionLanguage

Page 39: REAL SQL QUERIES

CHALLENGEQUESTION16:ONLINE/OFFLINEDifficulty:Beginner

Createasummarytablethatshows,byterritory,thepercentageofordersplacedonlineincomparisontoordersnotplacedonline.Youroutputshouldincludethefollowingcolumns:

TerritoryIDTotalordersPercentageofordersplacedonlinePercentageofordersnotplacedonline

Tomakethetableeasiertoread,displaypercentageswithapercentsignwithoutdecimals.Forexample,ninetyfivepercentwillbedisplayedas95%.

Page 40: REAL SQL QUERIES

CHALLENGEQUESTION17:LONGTIMENOSALEDifficulty:Intermediate

Thesalesdepartmentwillvisitstoreswithoutrecentsalesorders.Supposetoday’sdateisOctober7,2008.Createareportthatidentifiesstoresinwhichthelastorderdatewasatleast12monthsago.Youroutputshouldincludethefollowingcolumns:

BusinessEntityIDCustomerIDStoreIDStoreNameLastorderdateNumberofmonthssincelastorder

Page 41: REAL SQL QUERIES

CHALLENGEQUESTION18:COSTSVARYDifficulty:Intermediate

Ateamwasformedwiththegoalofreducingproductcosts.Helptheteamkickofftheirfirstmeetingbycompilingbaselinedataabouthistoricalproductcostvariability.QuerythedatabyProductID.Youroutputshouldincludethefollowing:

ProductIDProductNameSubCategoryMinimumhistoricalcostMaximumhistoricalcostHistoricalcostvariability(maximumhistoricalcostminusminimumhistoricalcost)Rankingofallhistoricalcostvariabilities(rankof“1”reflectstheproductIDexhibitingthegreatesthistoricalcostvariability)

Page 42: REAL SQL QUERIES

CHALLENGEQUESTION19:THERMOFORMTEMPERATUREDifficulty:Intermediate

Youareaskedtoreportthemostcommonreasonswhyproductswerescrappedthroughthemanufacturingprocess.CreateaquerybyProductIDthatincludesthefollowing:

ProductIDProductNameNumberofworkordersaffectedMostcommonscrapreason

Forexample,suppose“Thermoformtemperaturetoohigh”wasthemostcommonreasonwhyProductID398wasscrapped.Iftheproductwasscrapped100timesasaresultofthisreason,yourrowabouttheproductwouldappearasfollows:

Page 43: REAL SQL QUERIES

CHALLENGEQUESTION20:TORONTODifficulty:Intermediate

ProvideaddressdataaboutstoreswithmainofficeslocatedinToronto.Youroutputshouldincludethefollowingcolumns:

StorenameAddressLine1AddressLine2CityStateProvincePostalCode

Page 44: REAL SQL QUERIES

CHALLENGEQUESTION21:MARKETINGEMPLOYEESDifficulty:Intermediate

AnadministratorfromHumanResourcesasksyouforalistofemployeeswhoarecurrentlyintheMarketingdepartmentandwerehiredpriorto2002orlaterthan2004.Youroutputshouldincludethefollowingcolumns:

FirstNameLastNameJobTitleBirthDateMaritalStatusHireDate

Page 45: REAL SQL QUERIES

CHALLENGEQUESTION22:WHOLEFTTHATREVIEW?Difficulty:Intermediate

Theexecutiveswanttoknowifit’spossibletolinkpeoplewhohavemadeproductreviewswithcustomerdata.Theendgoalistolinksalesinformationtoproductreviews.Asafirststep,trylookingupBusinessEntityIDofreviewersbasedone-mailaddresses.Ifknown,BusinessEntityIDscanpointtosalesordersthroughCustomerIDs.Youroutputshouldincludethefollowingcolumns:

ProductReviewIDProductIDProductnameReviewerNameRatingReviewer’semailaddressReviewer’sBusinessEntityID(ifknown)

Page 46: REAL SQL QUERIES

CHALLENGEQUESTION23:LABELMIX-UPDifficulty:Intermediate

Someclothingitemsweremislabeled,andmanagementwillinformcustomers.Youareaskedtohelpbycompilingalistofaffectedcustomerswithphonenumbers.TheissuepertainstoallordersforshortsplacedonlineafterJuly7,2008.Yourlistshouldcontainthefollowingcolumns:

SalesOrderIDOrderDateProductNameCustomer’sfirstnameCustomer’slastnameCustomer’sphonenumber

Page 47: REAL SQL QUERIES

CHALLENGEQUESTION24:CLEARANCESALEDifficulty:Intermediate

TheMarketingdepartmentwillprepareamasse-mailtonotifyindividualretailcustomersaboutaclearancesale.Youareaskedtoreportthedepthofe-mailaddresseswithinthecompany’sdatabases.Accordingtherequestor,e-mailaddresscountsshouldbebasedone-mailpreferences.E-mailpreferencesarerecordedinthePerson.PersontablewithinthecolumnEmailPromotion.Utilizethefollowinge-mailpreferenceconversionsaspartofyouroutput:

Thevalue“0”indicates“Contactdoesnotwishtoreceivee-mailpromotions”Thevalue“1”indicates“Contactdoeswishtoreceivee-mailpromotionsfromAdventureWorks”Thevalue“2”indicates“Contactdoeswishtoreceivee-mailpromotionsfromAdventureWorksandselectedpartners”

Exampleoutput:

Page 48: REAL SQL QUERIES

CHALLENGEQUESTION25:TOPTERRITORIESDifficulty:Intermediate

Intermsofrevenue,whichtwosalesterritoriesweretopperformersduringfiscalyears2006and2007?

Notes:

ForAdventureWorks,thefiscalyearspansJulythroughJuneTaxandfreightwillnotbeconsideredwithrevenue

Youroutputshouldincludethefollowingcolumns:

FiscalyearTerritorynameRevenueTerritoryrank

Page 49: REAL SQL QUERIES

CHALLENGEQUESTION26:COMMISSIONPERCENTAGESDifficulty:Beginner

Rankcommissionpercentagesbysalesperson.Notes:

Arankof“1”shouldrelatetothesalespersonwiththegreatestcommissionpercentageIfcommissionpercentagesareequalamongsalespeople,rankbyBonusindescendingorder

Yoursolutionshouldincludethefollowingcolumns:

BusinessEntityIDCommissionpercentBonusRank

Page 50: REAL SQL QUERIES

CHALLENGEQUESTION27:WORKORDERSDifficulty:Beginner

PARTITheProductiondepartmentasksyoutoreportthenumberofworkordersbyProductID.Orderyourresultsfromthegreatestnumberofworkorderstotheleast.

PARTIIReportthenumberofworkordersbyproductname.Orderyourresultsfromthegreatestnumberofworkorderstotheleast.

Page 51: REAL SQL QUERIES

CHALLENGEQUESTION28:REVENUETRENDEDDifficulty:Intermediate

PARTISupposetoday’sdateisMay24,2008.UsingonlyrevenueinformationfromMay1throughMay23,estimaterevenueforthewholemonthofMay.Notes:

DatesarebasedonOrderDateTaxandfreightwillnotbeconsideredwithrevenue

Youroutputshouldincludethefollowingcolumns:

NumberofdaysinmonthsofarTotalrevenueinmonthsofarRevenueperdayforthemonthsofarMonthlyrevenuetrendedforallofMay

PARTIIForthesakeofcomparison,pulltheactualrevenueinformation.Youroutputshouldincludethefollowingcolumns:

ActualrevenueperdayActualrevenue

Page 52: REAL SQL QUERIES

CHALLENGEQUESTION29:SEPARATIONDifficulty:Intermediate

TheHumanResources.EmployeetableincludesthecolumnLoginIDinwhichusernamesanddomainsarecombined.Inyourquery,separatethenamesfromthedomains.Youroutputshouldincludethefollowing:

BusinessEntityIDLoginID(forexample,adventure-works\ken0)Domain(forexample,adventure-works)Username(forexample,ken0)

Page 53: REAL SQL QUERIES

CHALLENGEQUESTION30:SHIFTCOVERAGEDifficulty:Intermediate

ManagementwillreviewthecurrentdistributionoflaborbyshiftwithintheProductiondepartment.Createareportthatincludesthefollowing:

Departmentname(Production)ShiftnameNumberofemployees

Page 54: REAL SQL QUERIES

CHALLENGEQUESTION31:LABELSDifficulty:Beginner

Labelsrepresentingproductsizeswillbeappliedtotheboxesandpackagesofsomeproducts.Thevarietyoflabelsinclude“S”(size“Small”),“M”(size“Medium”),“L”(size“Large”),and“XL”(size“ExtraLarge”).

PARTIWriteaquerytodetermineifthevarietyoflabelsissufficienttocoverallalpha-sizedproducts.Forexample,since“2XL”labelsdonotexist,nolabelcouldbeappliedtoa“2XL”product.Ifa“2XL”productexisted,thevarietyoflabelswouldbeinsufficient.

PARTIISuppose1,000labelsareavailableineachsize.Calculatethenumberofadditionallabelsneededtocoveralltherelevantproductsintheinventory.Bysize,createatablethatincludesthefollowingcolumns:

SizeCurrentquantityAdditionallabelsneeded

Page 55: REAL SQL QUERIES

CHALLENGEQUESTION32:EMPLOYMENTSURVEYDifficulty:Intermediate

AdventureWorkswillparticipateinathird-partyemploymentsurveyamongbicyclemanufacturers.TheHumanResourcesdepartmentasksyoutohelppreparedatatosubmit.

PARTIProvidethefollowing:

TotalnumberofemployeesthroughoutthecompanyPercentageofemployeeswhoareMalePercentageofemployeeswhoareFemaleAveragenumberofmonthsofemployment.PretendtodayisJanuary1,2008.

Sampleoutput:

PARTIIDivideemployeedataintoquartilesbasedonaveragenumberofmonthsofemployment.Byquartile,providethefollowing:

TotalnumberofemployeesthroughoutthecompanyPercentageofemployeeswhoareMalePercentageofemployeeswhoareFemaleAveragenumberofmonthsemployed.PretendtodayisJanuary1,2008.

Sampleoutput:

Page 56: REAL SQL QUERIES

CHALLENGEQUESTION33:AGEGROUPSDifficulty:Intermediate

Inthepreviousquestion,youprovideddataforathird-partyemploymentsurveyamongbicyclemanufacturers.Moreinformationisneeded.Createaquerysummarizingpayratesandagegroupsbyjobtitle.AssumetodayisJanuary1,2008.Youroutputshouldbestructuredwiththefollowingcolumns:

JobTitleAgegroup,inyears,categorizedasfollows:

<1818–3536–5051–6061+

PayrateNumberofemployees

Asanexample,if10ProductionAssistantswere39yearsoldonJanuary1,2008,andtheirpayratewas23.65,thecorrespondingoutputrowwouldappearasfollows:

Page 57: REAL SQL QUERIES

CHALLENGEQUESTION34:REVENUEBYSTATEDifficulty:Beginner

Reportrevenuebystatein2006.Orderthedatafromstateswiththegreatestrevenuetostateswiththeleastrevenue.Notes:

DatesbasedonOrderDateRevenueincludestaxandfreightStatesbasedonshippingaddress

Page 58: REAL SQL QUERIES

CHALLENGEQUESTION35:TWOFREEBIKESDifficulty:Intermediate

Twoemployeesaregivenfreebicyclesatthestartofeachquarterlymeeting.Theemployeesarechosenatrandom,witheligibilitylimitedtotheleastseniorpositions.Createaviewtogenerateemployeenames.Theviewshouldincludethefollowingcolumns:

FirstNameLastNameJobTitle

Page 59: REAL SQL QUERIES

CHALLENGEQUESTION36:VOLUMEDISCOUNTSDifficulty:Intermediate

Youareaskedtoreportdataaboutvolumediscounts.

PARTICreateaqueryaboutsalesordersthatutilizedvolumediscounts.Youroutputshouldincludethefollowingcolumns:

SalesOrderIDOrderDateTotalvolumediscount(thesumofvolumediscountsappliedtotheorder)

PARTIISummarizedatafromPartIbyorderyear.Includethefollowing:

OrderyearTotalvolumediscount

Page 60: REAL SQL QUERIES

CHALLENGEQUESTION37:OVERPAYINGDifficulty:Intermediate

Someproductsarepurchasedfrommultiplevendors.Concernedaboutoverpayingforproducts,theexecutiveteamaskstoseepricecomparisonsamongvendors.

UsingthePurchasing.ProductVendortableexclusively,determineifproductsarepurchasedatsignificantlylowerpricesfromonevendortoanother.ByProductID,createaquerytoreturnthefollowinginformation:

ProductIDMostexpensivepriceSecondmostexpensivepricePercentdifferencefrommostexpensivepricetosecondmostexpensive(expressedasatwo-digitdecimal.Forexample,a93%pricedifferencewillbedisplayedas0.93).

Page 61: REAL SQL QUERIES

CHALLENGEQUESTION38:MARGINSDifficulty:Intermediate

Createaquerycalculatingtheprofitmarginsofbikemodels.

Notes:

ProfitmarginisbasedonthepercentdifferencebetweenListPriceandStandardCostOnlyconsiderbikemodelscurrentlysold

Youroutputshouldcontainthefollowingcolumns,withmodelsexhibitingthegreatestprofitmarginslistedfirst.

ProductModelIDProductnameProfitmargin(expressedasatwo-digitdecimal.Forexample,a93%profitmarginwillbedisplayedas0.93)

Page 62: REAL SQL QUERIES

CHALLENGEQUESTION39:PERCENTTOQUOTADifficulty:Intermediate

EachsalespersonissubjecttoaquarterlyquotastatedwithintheSales.SalesPersonQuotaHistorytable.TheQuotaDatecolumnrepresentsthefirstdateofthequotaquarter.

PARTIBuildatabletoshowthequota,actualsales,andpercenttoquotaforeachquarterandsalesperson.StoreyourdatainatemporarytabletobeutilizedinPartII.Note:Donotincludetaxandfreightwithrevenue.Yourresultsshouldcontainthefollowingcolumns:

BusinessEntityIDQuotadateSalesquotaActualsalesPercenttoquota

SortdatabyBusinessEntityIDfollowedbyquotadate.

PARTIISummarizeresultsfromPartIbysalesperson,byyear.Includethefollowing:

BusinessEntityIDQuotayearTotalquotaTotalsalesTotalpercenttoquotaAveragequarterlypercenttoquota

SortoutputbyBusinessEntityIDfollowedbyQuotayear.

Page 63: REAL SQL QUERIES

CHALLENGEQUESTION40:REVENUERANGESDifficulty:Beginner

Basedonsalesdatafrom2005,calculatethenumberofsalesorderswithineachofthefollowingrevenueranges:

1. $0-$1002. $100-$5003. $500-$1,0004. $1,000-$2,5005. $2,500-$5,0006. $5,000-$10,0007. $10,000-$50,0008. $50,000-$100,0009. >$100,000

Notes:RevenueincludestaxandfreightDatesbasedonOrderDate

CreateaSortIDtosortyourresultsinthesequencepresentedabove.Exampleoutput:

Page 64: REAL SQL QUERIES

CHALLENGEQUESTION41:E-MAILMYSTERYDifficulty:Intermediate

Asalespersonwasunabletolocateareturningcustomer’saccountbye-mailaddress.Frustrated,hepulleduptheaccountbythecustomer’slastname.Withtheaccountinformationonhisscreen,herealizedwhyhiscustomer’se-mailaddresswasnotfound.Thecustomer’se-mailaddressappearedasan“adventure-works.com”address,ratherthan“gmail.com.”Examinetheprevalenceofadventure-works.come-mailaddressesthroughoutthecompany’sdatabase.CreateaquerybyPersonType,withthefollowingoutput:

PersonTypeNumberofe-mailaddressescontainingtheadventure-works.comdomainNumberofe-mailaddressesnotcontainingtheadventure-works.comdomainTotalnumberofe-mailaddresses

Displayyourresultsbythegreatestnumberofe-mailaddressestothefewestnumberofe-mailaddresses.

Page 65: REAL SQL QUERIES

CHALLENGEQUESTION42:THEMENTORSDifficulty:Intermediate

TheVicePresidentofSaleswantsthefivemostsuccessfulsalespeopletomentorthefiveleastsuccessfulsalespeople.Createalistofsalespeopletomatchwithoneanother.Notes:

Successismeasuredby2008revenue.DatesarebasedonOrderDate.Donotconsidertaxandfreightwithrevenue.IgnoreorderswithnoSalesPersonID.

Youroutputshouldcontainthefollowingcolumns:SalesPersonIDofthesuccessfulsalespersonRevenueofthesuccessfulsalespersonSalesPersonIDoftheunsuccessfulsalespersonRevenueofthesuccessfulsalesperson

Forexample,supposethesalespersonwithSalesPersonID10wasthemostsuccessfulsalespersonandherrevenuewas$1,000.IfthesalespersonwithSalesPersonID20wastheleastsuccessfulsalespersonandherrevenuewas$200,thenthefirstrowofyourfive-rowoutputwouldappearasfollows:

Page 66: REAL SQL QUERIES

CHALLENGEQUESTION43:CALENDAROFWORKDAYSDifficulty:Advanced

Calculatethenumberofworkdaysineachyear,withoutconsiderationforholidays,tohelpforecastenergycosts.UsethisexerciseasanopportunitytocreateacomprehensivecalendarofworkdayspresentineachyearfromJanuary1,1990toJanuary1,2015tobeusedforfuturepurposes.Saveyourcalendarofworkdaysasatable.Yourtableshouldcontainthefollowingcolumns:

DateID(uniqueidentifier)Date(forexample,1990-01-2000:00:00.000)TextMonth(forexample,January1990)DateMonth(forexample,1990-01-0100:00:00.000)DayOfWeek(forexample,Monday)IsBusinessDay(0or1)

Basedonthetableyoucreated,summarizethenumberofworkingdaysperyearwiththefollowingcolumns:

YearBusinessDays

Page 67: REAL SQL QUERIES

CHALLENGEQUESTION44:ANNUALSALARYBYEMPLOYEEDifficulty:Advanced

Createaquerytoshowannualsalarybyemployeefrom2005to2008.Assumptions:

Today’sdateisJanuary1,2009TheRatecolumnwithinHumanResources.EmployeePayHistoryrepresentshourlypayratesEachemployeeworkseighthoursperday,MondaythroughFriday

Notes:HolidaysshouldnotbeconsideredYoumayutilizethecalendarofworkdayscreatedfromChallengeQuestion43.Itwouldbehelpfultoutilizetemporarytables;thenextchallengequestionwillincorporateinformationfromthisexercise

Page 68: REAL SQL QUERIES

CHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENTDifficulty:Advanced

TheVicePresidentofHumanResourcesreviewedyourreportaboutannualsalariesfromChallengeQuestion44.Helikedyourworkandheaskedtoseedatafromanadditionalperspective.Writeaqueryaboutannualsalariesbydepartmentfrom2008.Youroutputshouldincludethefollowingcolumns:

DepartmentIDMinimumsalaryAveragesalaryMaximumsalary

Page 69: REAL SQL QUERIES

CHALLENGEQUESTION46:HOLIDAYBONUSDifficulty:Beginner

HumanResourceswillissueholidaybonusestosalariedemployees.Thebonusamountwillequalcurrentpayratemultipliedby50.Forexample,anemployeeearning$10perhourwillreceiveaholidaybonusof$500.Calculateholidaybonuses.Youroutputshouldincludethefollowingcolumns:

BusinessEntityIDFirstNameLastNameJobTitleBonus

Page 70: REAL SQL QUERIES

CHALLENGEQUESTION47:COMPANYPICNICDifficulty:Intermediate

Nametagswillbeprintedforacompanypicnic.Youareaskedtohelppreparealistofemployeenames.Createaqueryinwhichfirstnames,lastnames,andsuffixesareconsolidatedintoonevalue,withacommaandaspaceseparatingthelastnamefromthesuffix.Forexample,ifFirstName=David,LastName=Baez,andSuffix=Jr,thenamewouldbeconsolidatedasDavidBaez,Jr.IfSuffixisNULL,thenameappearsasDavidBaez.Inall,youroutputshouldcontainthefollowingcolumns:

BusinessEntityIDFullnameDepartment

Displaythelistalphabeticallybydepartmentfollowedbyfullname.

Page 71: REAL SQL QUERIES

CHALLENGEQUESTION48:SALESQUOTACHANGESDifficulty:Intermediate

Managementwillreviewsalesquotachangesfrom2006through2007.Createareport,bysalesperson,thatincludesthefollowinginformation:

BusinessEntityIDLastNameSalesquotafromthestartof2006(firstquarter)Salesquotafromtheendof2007(lastquarter)Percentchangeinsalesquotas

Forsoundcomparisons,donotincludeinformationaboutsalespeoplewhowerenotassignedsalesquotasduringthestartof2007ortheendof2007.

Page 72: REAL SQL QUERIES

CHALLENGEQUESTION49:SCRAPRATEDifficulty:Intermediate

TheProductiondepartmentisconcernedaboutworkordersinwhichscrapratesexceed3%.Scraprateequalsscrappedquantitydividedbyorderquantity.Createaviewthatdisplays,bymostrecentduedates,thetop10%ofworkordersinwhichthescrapratewasgreaterthan3%,orderedbymostrecentduedate.Yourviewshouldcontainthefollowing:

WorkOrderIDDueDateProductNameScrapreasonScrappedquantityOrderquantityPercentscrapped

Exampleoutput:

Page 73: REAL SQL QUERIES

CHALLENGEQUESTION50:REASONSDifficulty:Intermediate

AdventureWorkscollectsdataonsomecustomer’sreasonsforpurchasing(seenonSales.SalesOrderHeaderSalesReason).Sometimes,customersciteonereason,like“Price,”fororderingaproduct.Othertimes,customerscitemultiplereasons,like“Price”and“Quality.”

Createaqueryaboutsalesorderreasons.Whenasalesorderhasonlyonereason,categorizeas“ExclusiveReason.”Whenasalesorderhasmorethanonereason,categorizeas“ContributingReason.”Then,createasummarycountofsalesordersbyreasonnameandyournewlycreatedReasonInfluencecolumn(ExclusiveReasonorContributingReason).

Basedonthedirectionsstatedabove,youroutputwillcontainthefollowingcolumns:

ReasonNameReasonInfluence(ExclusiveReasonorContributingReason)SalesOrderCount

Page 74: REAL SQL QUERIES

CHALLENGEQUESTION51:EXCESSINVENTORYDifficulty:Intermediate

Occasionally,AdventureWorkshasexcessinventoryonsomeofitsproducts.Toselltheseoverstockedproductsquickly,thecompanycreatesspecialdiscounts.

PARTITohelpchoosethediscountpercentagetobeapplied,createaqueryabouthistoricalexcessinventorydiscounts.PullalistofthepreviousexcessinventorydiscountsAdventureWorkshascreated.Youroutputshouldcontainthefollowingcolumns:

SpecialOfferIDDiscounttype(ExcessInventory)DiscountdescriptionDiscountcategory(CustomerorReseller)DiscountstartdateDiscountenddateDiscountpercentage

PARTIIAddanadditionalcolumntotheoutputfromPartI.Listthenumberofsalesordersinwhichthediscountwasutilized.

Page 75: REAL SQL QUERIES

CHALLENGEQUESTION52:PAYRATECHANGESDifficulty:Intermediate

HumanResourceswillreviewpayincreases.Foreachemployee,reportthelatestpayrateandthepayratepriortothelatestrate.Youroutputshouldincludethefollowingcolumns:

BusinessEntityIDPreviousrate(Payratepriortothelatestrate)LatestpayratePercentchangefrompreviousratetolatestpayrate.Expressthepercentincreasewithtwodigitsfollowedbyapercentsign.Forexample,10.01%.

Page 76: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTIONS

Page 77: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION1:YEAROVERYEARCOMPARISONS

KeyTable:Sales.SalesOrderHeaderKeyTable:Person.Person

StrategyStep1:

Organizesalesbysalesperson,fiscalyear,andfiscalquarterExcludeonlineordersStoreresultsintemptable

StrategyStep2:

Findsalesofthesamequarterofthepreviousfiscalyearbyjoiningtothetemptable

Page 78: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION2:THE2/22PROMOTION

KeyTable:Sales.SalesOrderHeaderKeyTable:Person.BusinessEntityAddressKeyTable:Person.AddressKeyTable:Person.StateProvince

Page 79: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

KeyTable:Sales.SalesOrderHeaderKeyColumn:OrderDateKeyColumn:SubTotal

Page 80: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION4:UPSELLTUESDAYS

KeyTable:Sales.SalesOrderHeaderKeyColumn:OnlineOrderFlagKeyFunction:DATENAME

Page 81: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION5:EXPIREDCREDITCARDS

KeyTable:Sales.CreditCardKeyFunction:EOMONTHKeyFunction:DATEFROMPARTSKeyTable:Sales.SalesOrderHeader

Page 82: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION6:PRINTCATALOG

KeyTable:Production.ProductKeyColumn:SellEndDateKeyColumn:FinishedGoodsFlagKeyTable:Production.ProductInventory

Page 83: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION7:SPECIALTEAM

KeyTable:Sales.SalesOrderHeaderKeyTable:Sales.SalesTerritoryHistoryKeyColumn:EndDateKeyTable:Person.Person

Page 84: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION8:KNAPSACKPROBLEM

Strategy:AddsalarydatatoresultsfromChallengeQuestion4Createthreetables,onerelatedtoeachterritoryCROSSJOINtablesSelectbestcombinationfromeightpossibilities

Page 85: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION9:PRODUCTCOMBINATIONS

Strategy:Buildatemporarytablewithinformationaboutallsalesorders.Thetablewillbeutilizedthroughoutallpartsofthesolution.Itshouldincludeatleastthefollowingcolumns:

CustomerIDSalesOrderIDProductTypeProductLineProductID

KeyTable:Sales.SalesOrderHeaderKeyTable:Sales.SalesOrderDetailKeyTable:Production.ProductKeyTable:Production.ProductSubcategoryKeyTable:Production.ProductCategoryKeyFunction:PIVOT

Page 86: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION10:MEDIANREVENUE

KeyTable:Sales.SalesOrderHeaderStrategy:

CreatearownumberforeveryorderwithineachyearDeterminethemaximumnumberofordersforeachyearFindtheorderwithrownumberequaltohalfofthemaximumnumberoforders

KeyFunction:PERCENTILE_DISC

Page 87: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION11:NEEDYACCOUNTANT

KeyTable:Sales.SalesTaxRateKeyTable:Person.StateProvinceKeyTable:Person.CountryRegion

Page 88: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION12:PRODUCTINVENTORYUPDATES

KeyTable:Production.ProductInventoryKeyFunction:GROUPINGKeyOperator:ROLLUP

Page 89: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION13:VACATIONHOURS

KeyTable:HumanResources.EmployeeKeyFunction:RIGHT

Page 90: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION14:PURCHASING

KeyTable:Purchasing.PurchaseOrderDetailKeyTable:Production.ProductKeyTable:Purchasing.PurchaseOrderHeader

Page 91: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION15:INTERPRETATIONNEEDED

KeyTable:Production.ProductDescriptionKeyTable:Production.ProductModelProductDescriptionCultureKeyTable:Production.ProductModelKeyTable:Production.Culture

Page 92: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION16:ONLINE/OFFLINE

KeyTable:Sales.SalesOrderHeaderKeyColumn:OnlineOrderFlagKeyFunction:CONVERTKeyFunction:ROUND

Page 93: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION17:LONGTIMENOSALE

KeyTable:Sales.SalesOrderHeaderKeyTable:Sales.CustomerKeyTable:Sales.StoreKeyFunction:DATEDIFF

Page 94: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION18:COSTSVARY

KeyTable:Production.ProductCostHistoryKeyTable:Production.ProductKeyTable:Production.ProductSubcategoryKeyFunction:DENSE_RANK

Page 95: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION19:THERMOFORMTEMPERATURE

KeyTable:Production.WorkOrderKeyTable:Production.ProductKeyTable:Production.ScrapReason

Page 96: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION20:TORONTO

KeyTable:Person.BusinessEntityAddressKeyTable:Person.AddressKeyTable:Person.AddressTypeKeyTable:Sales.Store

Page 97: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION21:MARKETINGEMPLOYEES

KeyTable:HumanResources.EmployeeDepartmentHistoryKeyColumn:EndDate(NULLindicatesthecurrentdepartment)KeyTable:HumanResources.DepartmentKeyTable:Person.PersonKeyTable:HumanResources.Employee

Page 98: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION22:WHOLEFTTHATREVIEW?

KeyTable:Production.ProductReviewKeyTable:Production.ProductKeyTable:Person.EmailAddress

Page 99: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION23:LABELMIX-UP

KeyTable:Sales.SalesOrderDetailKeyTable:Production.ProductKeyTable:Sales.SalesOrderHeaderKeyTable:Sales.CustomerKeyTable:Person.PersonKeyTable:Person.PersonPhone

Page 100: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION24:CLEARANCESALE

KeyTable:Person.EmailAddressKeyTable:Person.PersonKeyColumn:PersonTypeKeyValue:IN(tolocateindividualretailcustomers)

Page 101: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION25:TOPTERRITORIES

KeyTable:Sales.SalesOrderHeaderKeyTable:Sales.SalesTerritoryKeyFunction:DENSE_RANK

Page 102: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION26:COMMISSIONPERCENTAGES

KeyTable:Sales.SalesPersonKeyFunction:DENSE_RANK

Page 103: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION27:WORKORDERS

KeyTable:Production.WorkOrder

Page 104: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION28:REVENUETRENDED

KeyTable:Sales.SalesOrderHeaderKeyColumn:SubtotalKeyFunction:EOMONTH

Page 105: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION29:SEPARATION

KeyTable:HumanResources.EmployeeKeyFunction:LEFTKeyFunction:CHARINDEXKeyFunction:RIGHTKeyFunction:LEN

Page 106: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION30:SHIFTCOVERAGE

KeyTable:HumanResources.EmployeeDepartmentHistoryKeyColumn:EndDateKeyTable:HumanResources.DepartmentKeyTable:HumanResources.Shift

Page 107: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION31:LABELS

PARTIKeyTable:Production.ProductKeyFunction:ISNUMERIC

PARTIIKeyTable:Production.ProductKeyTable:Production.ProductInventory

Page 108: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION32:EMPLOYMENTSURVEY

KeyTable:HumanResources.EmployeeKeyFunction:DATEDIFFKeyFunction:NTILE

Page 109: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION33:AGEGROUPS

KeyTable:HumanResources.EmployeeKeyFunction:DATEDIFFKeyTable:HumanResources.EmployeePayHistory

Page 110: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION34:REVENUEBYSTATE

KeyTable:Sales.SalesOrderHeaderKeyTable:Person.AddressKeyTable:Person.StateProvince

Page 111: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION35:TWOFREEBIKES

KeyTable:HumanResources.Employee.

KeyColumn:OrganizationalLevel.InterpretthevaluesofOrganizationalLevelappropriatelybyexaminingthevaluesofvarioussenior-leveljobtitles.

KeyTable:Person.Person

Page 112: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION36:VOLUMEDISCOUNTS

KeyTable:Sales.SalesOrderDetailKeyTable:Sales.SpecialOfferKeyColumn:TypeKeyTable:Sales.SalesOrderHeader

Page 113: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION37:OVERPAYING

KeyTable:Purchasing.ProductVendorKeyColumn:LastReceiptCost

Page 114: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION38:MARGINS

KeyTable:Production.ProductKeyColumn:SellEndDateKeyTable:Production.ProductSubcategoryKeyTable:Production.ProductCategoryKeyTable:Production.ProductModel

Page 115: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION39:PERCENTTOQUOTA

KeyTable:Sales.SalesPersonQuotaHistoryKeyColumn:QuotaDateKeyTable:Sales.SalesOrderHeader

KeyConsideration:Searchforsalesthroughouttheentirequarter.SinceQuotaDaterepresentsthestartofeachquarter,thefunctionDATEADDcanbeusedtoextendthedaterange.

Page 116: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION40:REVENUERANGES

KeyTable:Sales.SalesOrderHeaderKeyColumn:TotalDueKeyExpression:CASE

Page 117: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION41:E-MAILMYSTERY

KeyTable:Person.EmailAddressKeyTable:Person.Person

Page 118: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION42:THEMENTORS

KeyTable:Sales.SalesOrderHeaderKeyColumn:SalesPersonIDKeyColumn:SubtotalKeyFunction:ROW_NUMBER

Page 119: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION43:CALENDAROFWORKDAYS

Strategytocreatethetableaboutworkdaysperyear:CreateashelltablewiththenecessarycolumnsCreatealoopthatrunsforthesameamountoftimesasrowsneededinthetableUpdatetablewithdetailsabouteachday

KeyFunctions:DATENAMEDATEADD

Page 120: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION44:ANNUALSALARYBYEMPLOYEE

Asshownbelow,someBusinessEntityID’swithintheHumanResources.EmployeePayHistorytableappearonmultiplerows:SELECTBusinessEntityIDFROMHumanResources.EmployeePayHistoryGROUPBYBusinessEntityIDHAVINGCOUNT(*)>1Eachrowmayrepresentapayratechangeforemployeeswithmultiplepayratesovertime.Strategy:

Identifythestartdate,enddate,andthenumberofbusinessdayscorrespondingtoeachemployee’srangeofdatesforeachpayrate.Tocountbusinessdays,utilizethecalendartableyoucreatedthroughthepreviouschallenge.

Page 121: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENT

YoumustaccountforthepossibilitythatanemployeecanswitchdepartmentsKeyTable:HumanResources.EmployeeDepartmentHistoryUtilizethecalendarofworkdaysfrompreviouschallengetofinddataaboutemployeepay

Page 122: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION46:HOLIDAYBONUS

KeyTable:HumanResources.EmployeeKeyColumn:SalariedFlagKeyTable:HumanResources.EmployeePayHistoryKeyTable:Person.Person

Page 123: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION47:COMPANYPICNIC

KeyTable:Person.PersonKeyColumn:PersonTypeKeyValues:SP(Salesperson),EM(non-salesemployee)KeyTable:HumanResources.EmployeeDepartmentHistoryKeyTable:HumanResources.Department

Page 124: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION48:SALESQUOTACHANGES

KeyTable:Sales.SalesQuotaPersonHistoryKeyTable:Person.Person

Page 125: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION49:SCRAPRATE

KeyTable:Production.WorkOrderKeyTable:Production.ScrapReasonKeyTable:Production.Product

Page 126: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION50:REASONS

KeyTable:Sales.SalesOrderHeaderSalesReasonKeyTable:Sales.SalesReason

Page 127: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION51:EXCESSINVENTORY

KeyTable:Sales.SpecialOfferKeyTable:Sales.SalesOrderDetail

Page 128: REAL SQL QUERIES

HINTSFORCHALLENGEQUESTION52:PAYRATECHANGES

KeyTable:HumanResources.EmployeePayHistoryKeyColumn:RateChangeDate

Page 129: REAL SQL QUERIES

SOLUTIONSTOCHALLENGEQUESTIONS

Solutionstochallengequestionsavailablefordownloadathttp://realsqlqueries.com.

Page 130: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION1:YEAROVERYEARCOMPARISONS

—DROPTABLE#data

SELECTSalesPersonID,FY=DATEPART(YEAR,DATEADD(MONTH,6,OrderDate)),FQ=DATEPART(QUARTER,DATEADD(MONTH,6,OrderDate)),FQSales=SUM(Subtotal)INTO#dataFROMSales.SalesOrderHeaderWHEREOnlineOrderFlag=0GROUPBYSalesPersonID,DATEPART(YEAR,DATEADD(MONTH,6,OrderDate)),DATEPART(QUARTER,DATEADD(MONTH,6,OrderDate))

SELECTN3.LastName,N1.*,SalesSameFQLastYr=N2.FQSales,Change=N1.FQSales-N2.FQSales,[%Change]=((N1.FQSales-N2.FQSales)/N2.FQSales)*100FROM#dataN1LEFTJOIN#DataN2ONN1.SalesPersonID=N2.SalesPersonIDANDN1.FQ=N2.FQANDN1.FY-1=N2.FYINNERJOINPerson.PersonN3ONN1.SalesPersonID=N3.BusinessEntityIDWHEREN1.FY=2008ORDERBYSalesPersonID,FYDESC,FQDESC

Page 131: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION2:THE2/22PROMOTION

—PartI

—DROPTABLE#data

SELECTN1.SalesOrderID,ShipToState=N4.Name,OrderDate=N1.OrderDate,[HistoricalOrder$]=N1.SubTotal,HistoricalFreight=N1.Freight,PotentialPromoEffect=CASEWHENN1.SubTotal>=1700ANDN1.SubTotal<2000THEN‘INCREASEORDERTO$2,000&PAY22CENTSFREIGHT’WHENN1.Subtotal>=2000THEN‘NOORDERCHANGEANDPAY22CENTSFREIGHT’ELSE‘NOORDERCHANGE&PAYHISTORICALFREIGHT’END,PotentialOrderGain=CASEWHENN1.SubTotal>=1700ANDN1.SubTotal<2000THEN2000-N1.SubTotalELSE0END,PotentialFreightLoss=CASEWHENN1.SubTotal>=1700THEN0.22ELSEN1.FreightEND-N1.Freight,[PromoNetGain/Loss]=CASEWHENN1.SubTotal>=1700ANDN1.SubTotal<2000THEN2000-N1.SubTotalELSE0END+CASEWHENN1.SubTotal>=1700

Page 132: REAL SQL QUERIES

THEN0.22ELSEN1.FreightEND-N1.FreightINTO#dataFROMSales.SalesOrderHeaderN1INNERJOINPerson.BusinessEntityAddressN2ONN1.ShipToAddressID=N2.AddressIDINNERJOINPerson.[Address]N3ONN2.AddressID=N3.AddressIDINNERJOINPerson.StateProvinceN4ONN3.StateProvinceID=N4.StateProvinceIDWHEREN4.Name=‘California’ANDDATEPART(YEAR,DATEADD(MONTH,6,N1.OrderDate))=2008

SELECT*FROM#data

—PartIISELECTPotentialPromoEffect,PotentialOrderGains=SUM(PotentialOrderGain),PotentialFreightLosses=SUM(PotentialFreightLoss),OverallNet=SUM([PromoNetGain/Loss])FROM#dataGROUPBYPotentialPromoEffect

Page 133: REAL SQL QUERIES

SOLUTION1TOCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

—DROPTABLE#Sales

SELECTFiscalYear=YEAR(DATEADD(MONTH,6,OrderDate)),OrderDate=CAST(OrderDateASDATE),OrderNumber=ROW_NUMBER()OVER(PARTITIONBYYEAR(DATEADD(MONTH,6,OrderDate))ORDERBYOrderDate),SubTotal,RunningTotal=CONVERT(FLOAT,NULL)INTO#SalesFROMSales.SalesOrderHeader

UPDATEN1SETRunningTotal=(SELECTSUM(SubTotal)FROM#SalesX1WHEREN1.FiscalYear=X1.FiscalYearANDX1.OrderNumber<=N1.OrderNumber)FROM#SalesN1

—DROPTABLE#FindOrder

SELECTFiscalYear,OrderNumberOver10M=(SELECTTOP1X1.OrderNumberFROM#SalesX1WHEREN1.FiscalYear=X1.FiscalYearANDX1.RunningTotal>=10000000ORDERBYX1.RunningTotal)INTO#FindOrderFROM#SalesN1GROUPBYN1.FiscalYear

SELECT

Page 134: REAL SQL QUERIES

N2.FiscalYear,N2.OrderDate,N2.OrderNumber,N2.RunningTotalFROM#FindOrderN1INNERJOIN#SalesN2ONN1.FiscalYear=N2.FiscalYearANDN1.OrderNumberOver10M=N2.OrderNumberWHEREN1.FiscalYearIN(2007,2008)

Page 135: REAL SQL QUERIES

SOLUTION2TOCHALLENGEQUESTION3:TENMILLIONDOLLARBENCHMARK

WITHFY2007AS(SELECTFY=2007,OrderDate=CAST(OrderDateASDATE),[OrderNumber]=ROW_NUMBER()OVER(ORDERBYSalesOrderID),RunningTotal=SUM(SubTotal)OVER(ORDERBYOrderdateROWSBETWEENUNBOUNDEDPRECEDINGANDCURRENTROW)FROMSales.SalesOrderHeaderWHEREDATEPART(YEAR,DATEADD(MONTH,6,OrderDate))=2007)

,FY2008AS(SELECTFY=2008,OrderDate=CAST(OrderDateASDATE),[OrderNumber]=ROW_NUMBER()OVER(ORDERBYSalesOrderID),RunningTotal=SUM(SubTotal)OVER(ORDERBYOrderdateROWSBETWEENUNBOUNDEDPRECEDINGANDCURRENTROW)FROMSales.SalesOrderHeaderWHEREDATEPART(YEAR,DATEADD(MONTH,6,OrderDate))=2008)

SELECTTOP1*FROMFY2007WHERERunningTotal>=10000000

UNION

SELECTTOP1*FROMFY2008WHERERunningTotal>=10000000

Page 136: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION4:UPSELLTUESDAYS

SELECTDayCategory=DATENAME(WEEKDAY,OrderDate),Revenue=SUM(Subtotal),Orders=COUNT(*),RevenuePerOrder=SUM(Subtotal)/COUNT(*)FROMSales.SalesOrderHeaderWHEREYEAR(OrderDate)=2008ANDOnlineOrderFlag=0GROUPBYDATENAME(WEEKDAY,OrderDate)ORDERBYRevenuePerOrderDESC

Page 137: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION5:EXPIREDCREDITCARDS

—PartI

—DROPTABLE#data

SELECTN1.CreditCardID,N1.CardType,ExpDate=EOMONTH(DATEFROMPARTS(N1.ExpYear,N1.ExpMonth,1)),LastOrderDate=CAST(N2.LastOrderDateASDATE),[Orders<=Exp]=COUNT(DISTINCTN3.SalesOrderID),[Orders>Exp]=COUNT(DISTINCTN4.SalesOrderID)INTO#dataFROMSales.CreditCardN1LEFTJOIN(SELECTX1.CreditCardID,LastOrderDate=MAX(X1.OrderDate)FROMSales.SalesOrderHeaderX1GROUPBYX1.CreditCardID)N2ONN1.CreditCardID=N2.CreditCardIDLEFTJOINSales.SalesOrderHeaderN3ONN1.CreditCardID=N3.CreditCardIDANDN3.OrderDate<=EOMONTH(DATEFROMPARTS(N1.ExpYear,N1.ExpMonth,1))LEFTJOINSales.SalesOrderHeaderN4ONN1.CreditCardID=N4.CreditCardIDANDN4.OrderDate>EOMONTH(DATEFROMPARTS(N1.ExpYear,N1.ExpMonth,1))GROUPBYN1.CreditCardID,N1.CardType,N2.LastOrderDate

Page 138: REAL SQL QUERIES

,N1.ExpYear,N1.ExpMonth

SELECT*FROM#dataORDERBY[Orders>Exp]DESC

—PartIISELECTCardType,[Orders<=Exp]=SUM([Orders<=Exp]),[Orders>Exp]=SUM([Orders>Exp])FROM#dataGROUPBYCardType

Page 139: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION6:PRINTCATALOG

SELECTN1.ProductID,ProductName=N1.Name,N1.Color,N1.ListPrice,N2.TotalQtyFROMProduction.ProductN1INNERJOIN(SELECTProductID,TotalQty=SUM(Quantity)FROMProduction.ProductInventoryGROUPBYProductID)N2ONN1.ProductID=N2.ProductIDWHEREN1.SellEndDateISNULLANDN2.TotalQty>=150ANDN1.ListPrice>=1500ANDN1.FinishedGoodsFlag=1

Page 140: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTIONS7:SPECIALTEAM

—DROPTABLE#2008RevbySalesPerson

SELECTSalesPersonID,[2008Sales]=SUM(Subtotal)INTO#2008RevbySalesPersonFROMSales.SalesOrderHeaderN1WHEREYEAR(N1.OrderDate)=2008GROUPBYSalesPersonID

—DROPTABLE#TerritoriesAndSales

SELECTN1.BusinessEntityID,N3.LastName,Territory=N2.Name,N4.[2008Sales]INTO#TerritoriesAndSalesFROMSales.SalesTerritoryHistoryN1INNERJOINSales.SalesTerritoryN2ONN1.TerritoryID=N2.TerritoryIDINNERJOINPerson.PersonN3ONN1.BusinessEntityID=N3.BusinessEntityIDINNERJOIN#2008RevbySalesPersonN4ONN1.BusinessEntityID=N4.SalesPersonIDWHEREN1.EndDateISNULLANDN2.NameIN(‘Northwest’,‘Southwest’,‘Canada’)

SELECT*FROM#TerritoriesAndSalesORDERBYTerritory,LastName

Page 141: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION8:KNAPSACKPROBLEM

Thesolutiontochallengequestion8beginswiththesolutiontochallengequestion7.

—DROPTABLE#2008RevbySalesPersonSELECTSalesPersonID,[2008Sales]=SUM(Subtotal)INTO#2008RevbySalesPersonFROMSales.SalesOrderHeaderN1WHEREYEAR(N1.OrderDate)=2008GROUPBYSalesPersonID

—DROPTABLE#TerritoriesAndSales

SELECTN1.BusinessEntityID,N3.LastName,Territory=N2.Name,N4.[2008Sales]INTO#TerritoriesAndSalesFROMSales.SalesTerritoryHistoryN1INNERJOINSales.SalesTerritoryN2ONN1.TerritoryID=N2.TerritoryIDINNERJOINPerson.PersonN3ONN1.BusinessEntityID=N3.BusinessEntityIDINNERJOIN#2008RevbySalesPersonN4ONN1.BusinessEntityID=N4.SalesPersonIDWHEREN1.EndDateISNULLANDN2.NameIN(‘Northwest’,‘Southwest’,‘Canada’)

SELECT*FROM#TerritoriesAndSalesORDERBYTerritory,LastName

ALTERTABLE#TerritoriesAndSalesADDSalaryMONEY

UPDATEN1SETSalary=CASE

Page 142: REAL SQL QUERIES

WHENLastName=‘Pak’THEN79500WHENLastName=‘Vargas’THEN60000WHENLastName=‘Campbell’THEN59500WHENLastName=‘Mensa-Annan’THEN56000WHENLastName=‘Ito’THEN68000WHENLastName=‘Mitchell’THEN80000ENDFROM#TerritoriesAndSalesN1

—DROPTABLE#Canada—DROPTABLE#Northwest—DROPTABLE#Southwest

SELECT*INTO#CanadaFROM#TerritoriesAndSalesWHERETerritory=‘Canada’SELECT*INTO#NorthwestFROM#TerritoriesAndSalesWHERETerritory=‘Northwest’SELECT*INTO#SouthwestFROM#TerritoriesAndSalesWHERETerritory=‘Southwest’

—DROPTABLE#finalSELECTAggregateSalary=N1.Salary+N2.Salary+N3.Salary,AggregateSales=N1.[2008Sales]+N2.[2008Sales]+N3.[2008Sales],[1stTerritory]=N1.Territory,[1stSalesPerson]=N1.LastName,[1stSalesPersonSales]=N1.[2008Sales],[1stSalary]=N1.Salary,[2ndTerritory]=N2.Territory,[2ndSalesPerson]=N2.LastName

Page 143: REAL SQL QUERIES

,[2ndSalesPersonSales]=N2.[2008Sales],[2ndSalary]=N2.Salary,[3rdTerritory]=N3.Territory,[3rdSalesPerson]=N3.LastName,[3rdSalesPersonSales]=N3.[2008Sales],[3rdSalary]=N3.SalaryINTO#finalFROM#CanadaN1CROSSJOIN#NorthwestN2CROSSJOIN#SouthwestN3

SELECTTOP1*FROM#finalWHEREAggregateSalary<210000ORDERBYAggregateSalesDESC

Page 144: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION9:PRODUCTCOMBINATIONS

—Temptabletobeutilizedthroughoutallpartsofthesolution

—DROPTABLE#ProductSales

SELECTN1.CustomerID,N1.SalesOrderID,ProductType=N5.Name,N3.ProductLine,N3.ProductIDINTO#ProductSalesFROMSales.SalesOrderHeaderN1INNERJOINSales.SalesOrderDetailN2ONN1.SalesOrderID=N2.SalesOrderIDINNERJOINProduction.ProductN3ONN2.ProductID=N3.ProductIDINNERJOINProduction.ProductSubcategoryN4ONN3.ProductSubcategoryID=N4.ProductSubcategoryIDINNERJOINProduction.ProductCategoryN5ONN4.ProductCategoryID=N5.ProductCategoryID

—PartI

DECLARE@TotalOrdersFLOAT=(SELECTCOUNT(DISTINCTSalesOrderID)FROM#ProductSales)

DECLARE@BikeAccessoryOrdersFLOAT=(SELECTCOUNT(DISTINCTN1.SalesOrderID)FROM#ProductSalesN1INNERJOIN#ProductSalesN2ONN1.SalesOrderID=N2.SalesOrderIDWHEREN1.ProductType=‘Bikes’ANDN2.ProductType=‘Accessories’)

SELECTBikeAndAccessory=CONVERT(VARCHAR(10),CONVERT(DECIMAL(5,2),

Page 145: REAL SQL QUERIES

(@BikeAccessoryOrders/@TotalOrders)*100))+‘%’

DECLARE@BikeClothingOrdersFLOAT=(SELECTCOUNT(*)FROM(SELECTSalesOrderIDFROM#ProductSalesGROUPBYSalesOrderIDHAVINGSUM(CASEWHENProductType=‘Bikes’THEN1ELSE0END)>=1ANDSUM(CASEWHENProductType=‘Clothing’THEN1ELSE0END)>=2)X1)

SELECTBikeAndClothing=CONVERT(VARCHAR(10),CONVERT(DECIMAL(5,2),(@BikeClothingOrders/@TotalOrders)*100))+‘%’

—PartII

—DROPTABLE#Pivot

SELECT*INTO#PivotFROM(SELECTDISTINCTSalesOrderID,ProductType,Cnt=1FROM#ProductSales)N1

PIVOT(COUNT(Cnt)FORProductTypeIN([Bikes],[Accessories],[Clothing],[Components]))X1

Page 146: REAL SQL QUERIES

SELECTBikes,Accessories,Clothing,Components,Orders=COUNT(*)FROM#PivotGROUPBYBikes,Accessories,Clothing,ComponentsORDERBYBikes,Accessories,Clothing,Components

—PartIII

—DROPTABLE#Pivot2

SELECT*INTO#Pivot2FROM(SELECTDISTINCTCustomerID,ProductLine,Cnt=1FROM#ProductSales)N1PIVOT(COUNT(Cnt)FORProductLineIN([M],[S],[T],[R]))X1

SELECTM,S,T,R,Customers=COUNT(*)FROM#Pivot2GROUPBYM,S,T,RORDERBYM,S,T,R

Page 147: REAL SQL QUERIES

SOLUTION1TOCHALLENGEQUESTION10:MEDIANREVENUE

—DROPTABLE#Sales

SELECTOrderYear=YEAR(OrderDate),SubTotal,RowNumbForMedian=ROW_NUMBER()OVER(PARTITIONBYYEAR(OrderDate)ORDERBYSubTotal)INTO#SalesFROMSales.SalesOrderHeader

—DROPTABLE#SalesGrouped

SELECTOrderYear,NumbOrders=COUNT(*),NumbOrdersEven=CASEWHENCOUNT(*)%2=0THEN1ELSE0END,FindMedian=(COUNT(*)/2)+1,Median=CONVERT(FLOAT,NULL)INTO#SalesGroupedFROM#SalesGROUPBYOrderYear

UPDATEN1SETMedian=N2.SubTotalFROM#SalesGroupedN1INNERJOIN#SalesN2ONN1.OrderYear=N2.OrderYearANDN1.FindMedian=N2.RowNumbForMedianWHERENumbOrdersEven=0

UPDATEN1SETMedian=(SELECTAVG(SubTotal)FROM#SalesX1WHEREN1.OrderYear=X1.OrderYear

Page 148: REAL SQL QUERIES

ANDX1.RowNumbForMedianIN(N1.FindMedian,(N1.FindMedian-1)))FROM#SalesGroupedN1WHERENumbOrdersEven=1

SELECTN1.OrderYear,MinSale=MIN(SubTotal),MaxSale=MAX(SubTotal),AvgSale=AVG(SubTotal),MedianSale=N2.MedianFROM#SalesN1INNERJOIN#SalesGroupedN2ONN1.OrderYear=N2.OrderYearGROUPBYN1.OrderYear,N2.MedianORDERBYN1.OrderYear

Page 149: REAL SQL QUERIES

SOLUTION2TOCHALLENGEQUESTION10:MEDIANREVENUE

WITHMedianSalesAS(SELECTDISTINCTOrderYear=YEAR(OrderDate),MedianSale=PERCENTILE_DISC(0.5)WITHINGROUP(ORDERBYSubtotal)OVER(PARTITIONBYYEAR(OrderDate))FROMSales.SalesOrderHeader)

SELECTOrderYear=YEAR(N1.OrderDate),MinSale=MIN(N1.SubTotal),MaxSale=MAX(N1.SubTotal),AvgSale=AVG(N1.SubTotal),N2.MedianSaleFROMSales.SalesOrderHeaderN1INNERJOINMedianSalesN2ONYEAR(N1.OrderDate)=N2.OrderYearGROUPBYYEAR(N1.OrderDate),N2.MedianSaleORDERBYYEAR(N1.OrderDate)

Page 150: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION11:NEEDYACCOUNTANT

SELECTCountry=N3.Name,MaxTaxRate=MAX(N1.TaxRate)FROMSales.SalesTaxRateN1INNERJOINPerson.StateProvinceN2ONN1.StateProvinceID=N2.StateProvinceIDINNERJOINPerson.CountryRegionN3ONN2.CountryRegionCode=N3.CountryRegionCodeGROUPBYN3.Name

Page 151: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION12:PRODUCTINVENTORYUPDATES

—DROPVIEWProduction.Vw_Product_Inventory

CREATEVIEWProduction.Vw_Product_Inventory

AS

SELECTLocationID=CASEWHENGROUPING(LocationID)=1THENCONVERT(VARCHAR(5),‘Total’)ELSECONVERT(VARCHAR(5),LocationID)END,DistinctProducts=COUNT(DISTINCTProductID),Quantity=SUM(Quantity)FROMProduction.ProductInventoryGROUPBYLocationIDWITHROLLUP

Page 152: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION13:VACATIONHOURS

WITHMaxVacHrsAS(SELECTMaxVacHrs=MAX(VacationHours)FROMHumanResources.Employee)

SELECTNationalID=RIGHT(N1.NationalIDNumber,4),N2.FirstName,N2.LastName,N1.JobTitle,N1.VacationHoursFROMHumanResources.EmployeeN1INNERJOINPerson.PersonN2ONN1.BusinessEntityID=N2.BusinessEntityIDINNERJOINMaxVacHrsN3ONN1.VacationHours=N3.MaxVacHrs

Page 153: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION14:PURCHASING

SELECTN1.ProductID,ProductName=N2.Name,N3.OrderDate,QuantityOrdered=SUM(N1.OrderQty)FROMPurchasing.PurchaseOrderDetailN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDINNERJOINPurchasing.PurchaseOrderHeaderN3ONN1.PurchaseOrderID=N3.PurchaseOrderIDWHEREYEAR(N3.OrderDate)=2007GROUPBYN1.Productid,N2.Name,N3.OrderDateORDERBYSUM(N1.OrderQty)DESC

Page 154: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION15:INTERPRETATIONNEEDED

SELECTN2.ProductModelID,ProductModel=N3.Name,N1.[Description],[Language]=N4.NameFROMProduction.ProductDescriptionN1INNERJOINProduction.ProductModelProductDescriptionCultureN2ONN1.ProductDescriptionID=N2.ProductDescriptionIDINNERJOINProduction.ProductModelN3ONN2.ProductModelID=N3.ProductModelIDINNERJOINProduction.CultureN4ONN2.CultureID=N4.CultureIDWHEREN4.Name<>‘English’

Page 155: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION16:ONLINE/OFFLINE

SELECTTerritoryID,TotalOrders=COUNT(*),PercOnline=CONVERT(VARCHAR(50),ROUND((CONVERT(FLOAT,SUM(CASEWHENOnlineOrderFlag=1THEN1ELSE0END))/COUNT(*))*100,0))+‘%’,PercOffline=

CONVERT(VARCHAR(50),ROUND((CONVERT(FLOAT,SUM(CASEWHENOnlineOrderFlag=0THEN1ELSE0END))/COUNT(*))*100,0))+‘%’

FROMSales.SalesOrderHeaderGROUPBYTerritoryIDORDERBYTerritoryID

Page 156: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION17:LONGTIMENOSALE

WITHStoresAS(SELECTN3.BusinessEntityID,N1.CustomerID,N2.StoreID,StoreName=N3.Name,LastOrderDate=MAX(N1.OrderDate),MonthsSinceLastOrder=DATEDIFF(MONTH,MAX(N1.OrderDate),‘2008-10-07’)FROMSales.SalesOrderHeaderN1INNERJOINSales.CustomerN2ONN1.CustomerID=N2.CustomerIDINNERJOINSales.StoreN3ONN2.StoreID=N3.BusinessEntityIDGROUPBYN3.BusinessEntityID,N2.StoreID,N1.CustomerID,N3.Name)

SELECT*FROMStoresWHEREMonthsSinceLastOrder>=12ORDERBYMonthsSinceLastOrderDESC

Page 157: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION18:COSTSVARY

SELECTN1.ProductID,ProductName=N2.Name,SubCategory=N3.Name,MinCost=MIN(N1.StandardCost),MaxCost=MAX(N1.StandardCost),CostVar=MAX(N1.StandardCost)-MIN(N1.StandardCost),CostVarRank=CASEWHENMAX(N1.StandardCost)-MIN(N1.StandardCost)=0THEN0ELSEDENSE_RANK()OVER(ORDERBYMAX(N1.StandardCost)-MIN(N1.StandardCost)DESC)ENDFROMProduction.ProductCostHistoryN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDINNERJOINProduction.ProductSubcategoryN3ONN2.ProductSubcategoryID=N3.ProductSubcategoryIDGROUPBYN1.ProductID,N2.Name,N3.NameORDERBYMAX(N1.StandardCost)-MIN(N1.StandardCost)DESC

Page 158: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION19:THERMOFORMTEMPERATURE

WITHTempAS(SELECTRNK=ROW_NUMBER()OVER(PARTITIONBYN1.ProductIDORDERBYCOUNT(N2.Name)DESC),N1.ProductID,ProductName=N2.Name,WorkOrderCount=COUNT(N2.Name),ScrapReason=N3.NameFROMProduction.WorkOrderN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDINNERJOINProduction.ScrapReasonN3ONN1.ScrapReasonID=N3.ScrapReasonIDGROUPBYN1.ProductID,N2.Name,N3.Name)

SELECTProductID,ProductName,WorkOrderCount,ScrapReasonFROMTempWHERERNK=1ORDERBYWorkOrderCountDESC

Page 159: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION20:TOTONTO

SELECTAddressType=N3.Name,StoreName=N4.Name,N2.AddressLine1,N2.AddressLine2,N2.City,StateProvince=N5.Name,N2.PostalCodeFROMPerson.BusinessEntityAddressN1INNERJOINPerson.[Address]N2ONN1.AddressID=N2.AddressIDINNERJOINPerson.AddressTypeN3ONN1.AddressTypeID=N3.AddressTypeIDINNERJOINSales.StoreN4ONN1.BusinessEntityID=N4.BusinessEntityIDINNERJOINPerson.StateProvinceN5ONN2.StateProvinceID=N5.StateProvinceIDWHEREN3.Name=‘Mainoffice’andN2.City=‘Toronto’

Page 160: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION21:MARKETINGEMPLOYEES

SELECTN3.FirstName,N3.LastName,N4.JobTitle,N4.BirthDate,N4.MaritalStatus,N4.HireDateFROMHumanResources.EmployeeDepartmentHistoryN1INNERJOINHumanResources.DepartmentN2ONN1.DepartmentID=N2.DepartmentIDINNERJOINPerson.PersonN3ONN1.BusinessEntityID=N3.BusinessEntityIDINNERJOINHumanResources.EmployeeN4ONN1.BusinessEntityID=N4.BusinessEntityIDWHEREN2.Name=‘Marketing’AND((YEAR(N4.HireDate)<2002)ORYEAR(N4.HireDate)>2004)ANDN1.EndDateISNULL

Page 161: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION22:WHOLEFTTHATREVIEW?

SELECTN1.ProductReviewID,N1.ProductID,ProductName=N2.Name,N1.ReviewerName,N1.Rating,ReviewerEmail=N1.EmailAddress,N3.BusinessEntityIDFROMProduction.ProductReviewN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDLEFTJOINPerson.EmailAddressN3ONN1.EmailAddress=N3.EmailAddress—ExecutionreturnseachBusinessEntityIDasNULL.Itwillnotbepossibletolocatesalesordersrelatedtoproductreviewsbecausetherearenomatches.

Page 162: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION23:LABELMIX-UP

SELECTN1.SalesOrderID,N3.OrderDate,ProductName=N2.Name,N5.FirstName,N5.LastName,N6.PhoneNumberFROMSales.SalesOrderDetailN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDINNERJOINSales.SalesOrderHeaderN3ONN1.SalesOrderID=N3.SalesOrderIDINNERJOINSales.CustomerN4ONN3.CustomerID=N4.CustomerIDINNERJOINPerson.PersonN5ONN4.PersonID=N5.BusinessEntityIDINNERJOINPerson.PersonPhoneN6ONN5.BusinessEntityID=N6.BusinessEntityIDWHEREN2.Namelike‘%shorts%’ANDN3.OrderDate>‘2008-07-07’ANDN3.OnlineOrderFlag=1ORDERBYN1.SalesOrderID

Page 163: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION24:CLEARANCESALE

WITHEmailAS(SELECTN1.BusinessEntityID,N1.EmailAddress,EmailPref=CASEWHENN2.EmailPromotion=0THEN‘Contactdoesnotwishtoreceivee-mailpromotions’WHENN2.EmailPromotion=1THEN‘Contactdoeswishtoreceivee-mailpromotionsfromAdventureWorks’WHENN2.EmailPromotion=2THEN‘Contactdoeswishtoreceivee-mailpromotionsfromAdventureWorksandselectedpartners’ENDFROMPerson.EmailAddressN1LEFTJOINPerson.PersonN2ONN1.BusinessEntityID=N2.BusinessEntityIDWHEREN2.PersonType=‘IN’)

SELECTEmailPref,[Count]=COUNT(*)FROMEmailGROUPBYEmailPrefORDERBYCOUNT(*)DESC

Page 164: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION25:TOPTERRITORIES

WITHTerritoryRankAS(SELECTFY=YEAR(DATEADD(MONTH,6,N1.OrderDate)),Territory=N2.Name,Revenue=SUM(N1.SubTotal),[Territory$Rank]=DENSE_RANK()OVER(PARTITIONBYYEAR(DATEADD(MONTH,6,N1.OrderDate))ORDERBYSUM(N1.Subtotal)DESC)FROMSales.SalesOrderHeaderN1INNERJOINSales.SalesTerritoryN2ONN1.TerritoryID=N2.TerritoryIDGROUPBYYEAR(DATEADD(MONTH,6,N1.OrderDate)),N2.Name)

SELECT*FROMTerritoryRankWHEREFYIN(2006,2007)ANDTerritory$RankIN(1,2)ORDERBYFY,Territory$Rank

Page 165: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION26:COMMISSIONPERCENTAGES

SELECTBusinessEntityID,CommissionPct,Bonus,[Rank]=DENSE_RANK()OVER(ORDERBYCommissionPctDESC,BonusDESC)FROMSales.SalesPersonORDERBYCommissionPctDESC

Page 166: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION27:WORKORDERS

—PartI

SELECTProductID,WorkOrders=COUNT(*)FROMProduction.WorkOrderGROUPBYProductIDORDERBYCOUNT(*)DESC

—PartIISELECTProductName=N2.Name,WorkOrders=COUNT(*)FROMProduction.WorkOrderN1INNERJOINProduction.ProductN2ONN1.ProductID=N2.ProductIDGROUPBYN2.NameORDERBYCOUNT(*)DESC

Page 167: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION28:REVENUETRENDED

DECLARE@StartDateDATE=‘2008-05-01’DECLARE@EndDateDATE=‘2008-05-23’

—PartI:SELECTDaysInMonthSoFar=DATEDIFF(day,@StartDate,@EndDate)+1,RevenueInMonthSoFar=SUM(SubTotal),RevPerDayforMonthSoFar=(SUM(SubTotal)/(DATEDIFF(day,@StartDate,@EndDate)+1)),DaysInMonth=DAY(EOMONTH(@StartDate)),MonthlyRevTrended=SUM(SubTotal)/(DATEDIFF(day,@StartDate,@EndDate)+1)*DAY(EOMONTH(@StartDate))FROMSales.SalesOrderHeaderWHEREOrderDateBETWEEN@StartDateAND@EndDate

—PartII:SELECTActualPerDay=SUM(SubTotal)/DAY(EOMONTH(@StartDate)),ActualRev=SUM(Subtotal)FROMSales.SalesOrderHeaderWHEREOrderDateBETWEEN@StartDateANDEOMONTH(@EndDate)

Page 168: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION29:SEPARATION

SELECTBusinessEntityID,LoginID,Domain=LEFT(LoginID,CHARINDEX(‘',LoginID,1)-1),UserName=RIGHT(LoginID,LEN(LoginID)-CHARINDEX(‘',LoginID,1))FROMHumanResources.EmployeeORDERBYBusinessEntityID

Page 169: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION30:SHIFTCOVERAGE

SELECTDepartmentName=N2.Name,ShiftName=N3.Name,Employees=COUNT(*)FROMHumanResources.EmployeeDepartmentHistoryN1INNERJOINHumanResources.DepartmentN2ONN1.DepartmentID=N2.DepartmentIDINNERJOINHumanResources.[Shift]N3ONN1.ShiftID=N3.ShiftIDWHEREN2.Name=‘Production’ANDN1.EndDateISNULLGROUPBYN2.Name,N3.NameORDERBYN2.Name,N3.Name

Page 170: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION31:LABELS

—PartISELECTDISTINCTSizeFROMProduction.ProductWHEREISNUMERIC(Size)=0ANDSizeISNOTNULL

—Thevarietyofstickersisappropriateforassignmenttothecompany’sproducts.

—PartIISELECTN1.Size,CurrentQty=SUM(N2.Quantity),AdditLabelsNeeded=CASEWHENSUM(N2.Quantity)-1000<0THEN0ELSESUM(N2.Quantity)-1000ENDFROMProduction.ProductN1INNERJOINProduction.ProductInventoryN2ONN1.ProductID=N2.ProductIDWHEREISNUMERIC(N1.Size)=0ANDN1.SizeISNOTNULLGROUPBYN1.Size

Page 171: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION32:EMPLOYMENTSURVEY

—PartISELECTEmployees=COUNT(*),[%Male]=ROUND(SUM(CASEWHENGender=‘M’THEN1ELSE0END)/CONVERT(FLOAT,COUNT(*))*100,2),[%Female]=ROUND(SUM(CASEWHENGender=‘F’THEN1ELSE0END)/CONVERT(FLOAT,COUNT(*))*100,2),AvgMonthsEmp=AVG(DATEDIFF(MONTH,HireDate,‘2008-01-01’))FROMHumanResources.Employee

—PartII

SELECTX1.Quartile,Employees=COUNT(*),[%Male]=ROUND(SUM(CASEWHENX1.Gender=‘M’THEN1ELSE0END)

Page 172: REAL SQL QUERIES

/CONVERT(FLOAT,COUNT(*))*100,2),[%Female]=ROUND(SUM(CASEWHENX1.Gender=‘F’THEN1ELSE0END)/CONVERT(FLOAT,COUNT(*))*100,2),AvgMonthsEmp=AVG(X1.MonthsEmployed)FROM(SELECTBusinessEntityID,Quartile=NTILE(4)OVER(ORDERBYDATEDIFF(MONTH,HireDate,‘2008-01-01’)),HireDate,MonthsEmployed=DATEDIFF(MONTH,HireDate,‘2008-01-01’),GenderFROMHumanResources.Employee)X1GROUPBYX1.Quartile

Page 173: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION33:AGEGROUPS

SELECTN1.JobTitle,AgeGroup=CASEWHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<18THEN‘<18’WHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<35THEN‘18-35’WHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<50THEN‘36-50’WHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<60THEN‘51-60’ELSE‘61+’END,N2.Rate,Employees=COUNT(N1.BusinessEntityID)FROMHumanResources.EmployeeN1INNERJOINHumanResources.EmployeePayHistoryN2ONN1.BusinessEntityID=N2.BusinessEntityIDINNERJOIN(SELECTBusinessEntityID,RatechangeDate=MAX(RateChangeDate)FROMHumanResources.EmployeePayHistoryGROUPBYBusinessEntityID)N3ONN3.BusinessEntityID=N2.BusinessEntityIDANDN3.RatechangeDate=N2.RateChangeDateGROUPBYJobTitle,Rate,CASEWHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<18THEN‘<18’WHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<35THEN‘18-35’WHENDATEDIFF(

Page 174: REAL SQL QUERIES

YY,N1.BirthDate,‘2008-01-01’)<50THEN‘36-50’WHENDATEDIFF(YY,N1.BirthDate,‘2008-01-01’)<60THEN‘51-60’ELSE‘61+’END

Page 175: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION34:REVENUEBYSTATE

SELECT[State]=N3.Name,TotalSales=SUM(N1.TotalDue)FROMSales.SalesOrderHeaderN1INNERJOINPerson.[Address]N2ONN1.ShipToAddressID=N2.AddressIDINNERJOINPerson.StateProvinceN3ONN2.StateProvinceID=N3.StateProvinceIDWHEREYEAR(N1.OrderDate)=2006GROUPBYN3.NameORDERBYSUM(N1.TotalDue)DESC

Page 176: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION35:TWOFREEBIKES

—DROPVIEW—HumanResources.Vw_Employee_Bicycle_Giveaway

CREATEVIEWHumanResources.Vw_Employee_Bicycle_Giveaway

AS

SELECTTOP2N2.FirstName,N2.LastName,N1.JobTitleFROMHumanResources.EmployeeN1INNERJOINPerson.PersonN2ONN1.BusinessEntityID=N2.BusinessEntityIDWHEREN1.OrganizationLevel=(SELECTMAX(OrganizationLevel)FROMHumanResources.Employee)ORDERBYNEWID()

Page 177: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION36:VOLUMEDISCOUNTS

—DROPTABLE#data

SELECTN1.SalesOrderID,N3.OrderDate,TotalVolumeDiscount=SUM(N1.UnitPriceDiscount*N1.UnitPrice*N1.OrderQty)INTO#dataFROMSales.SalesOrderDetailN1INNERJOINSales.SpecialOfferN2ONN1.SpecialOfferID=N2.SpecialOfferIDINNERJOINSales.SalesOrderHeaderN3ONN1.SalesOrderID=N3.SalesOrderIDWHEREN2.[Type]=‘VolumeDiscount’GROUPBYN1.SalesOrderID,N2.[Type],N3.OrderDateHAVINGSUM(N1.UnitPriceDiscount*N1.UnitPrice*N1.OrderQty)>0

—PartISELECT*FROM#dataORDERBYSalesOrderID

—PartII

SELECTOrderYear=YEAR(OrderDate),TotalVolumeDiscount=SUM(TotalVolumeDiscount)FROM#dataGROUPBYYEAR(OrderDate)

Page 178: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION37:OVERPAYING

—DROPTABLE#ProductVendor

SELECTProductID,MostExpensivePrice=MAX(LastReceiptCost),SecondMostExpensivePrice=CONVERT(FLOAT,NULL),PercOverSecondPrice=CONVERT(FLOAT,NULL)INTO#ProductVendorFROMPurchasing.ProductVendorGROUPBYProductIDHAVINGCOUNT(DISTINCTLastReceiptCost)>1

UPDATEN1SETSecondMostExpensivePrice=(SELECTTOP1X1.LastReceiptCostFROMPurchasing.ProductVendorX1WHEREN1.ProductID=X1.ProductIDANDN1.MostExpensivePrice<>X1.LastReceiptCostORDERBYX1.LastReceiptCostDESC)FROM#ProductVendorN1

UPDATEN1SETPercOverSecondPrice=CONVERT(DECIMAL(10,2),CONVERT(FLOAT,(MostExpensivePrice-SecondMostExpensivePrice))/SecondMostExpensivePrice)FROM#ProductVendorN1

SELECT*FROM#ProductVendorORDERBYPercOverSecondPriceDESC

Page 179: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION38:MARGINS

SELECTN1.ProductModelID,ProductName=N4.Name,ProfitMargin=CONVERT(DECIMAL(10,2),CONVERT(FLOAT,(N1.ListPrice-N1.StandardCost))/N1.StandardCost)FROMProduction.ProductN1INNERJOINProduction.ProductSubcategoryN2ONN1.ProductSubcategoryID=N2.ProductSubcategoryIDINNERJOINProduction.ProductCategoryN3ONN2.ProductCategoryID=N3.ProductCategoryIDINNERJOINProduction.ProductModelN4ONN1.ProductModelID=N4.ProductModelIDWHEREN3.Name=‘Bikes’ANDN1.SellEndDateISNULLGROUPBYN1.ProductModelID,N4.Name,CONVERT(DECIMAL(10,2),CONVERT(FLOAT,(N1.ListPrice-N1.StandardCost))/N1.StandardCost)ORDERBYProfitMarginDESC

Page 180: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION39:PERCENTTOQUOTA

—PartI

—DROPTABLE#SalesQuotaSummary

SELECTN1.BusinessEntityID,N1.QuotaDate,N1.SalesQuota,ActualSales=CONVERT(DECIMAL(10,2),SUM(N2.SubTotal)),PercToQuota=CONVERT(DECIMAL(10,2),CONVERT(FLOAT,SUM(N2.SubTotal))/N1.SalesQuota)INTO#SalesQuotaSummaryFROMSales.SalesPersonQuotaHistoryN1LEFTJOINSales.SalesOrderHeaderN2ONN1.BusinessEntityID=N2.SalesPersonIDANDN2.OrderDate>=N1.QuotaDateANDN2.OrderDate<DATEADD(MONTH,3,N1.QuotaDate)GROUPBYN1.BusinessEntityID,N1.QuotaDate,N1.SalesQuota

SELECT*FROM#SalesQuotaSummaryORDERBYBusinessEntityID,QuotaDate

—PartII

SELECTBusinessEntityID,QuotaYear=YEAR(QuotaDate),TotalQuota=SUM(SalesQuota),TotalSales=SUM(ActualSales),TotalPercToQuota=CONVERT(DECIMAL(10,2),CONVERT(FLOAT,

Page 181: REAL SQL QUERIES

SUM(ActualSales))/SUM(SalesQuota)),AvgQrtlyPercToQuota=CONVERT(DECIMAL(10,2),AVG(PercToQuota))FROM#SalesQuotaSummaryGROUPBYBusinessEntityID,YEAR(QuotaDate)ORDERBYBusinessEntityID,YEAR(QuotaDate)

Page 182: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION40:REVENUERANGES

SELECTSortID=CASEWHENTotalDue<100THEN1WHENTotalDue<500THEN2WHENTotalDue<1000THEN3WHENTotalDue<2500THEN4WHENTotalDue<5000THEN5WHENTotalDue<10000THEN6WHENTotalDue<50000THEN7WHENTotalDue<100000THEN8ELSE9END,SalesAmountCategory=CASEWHENTotalDue<100THEN‘0-100’WHENTotalDue<500THEN‘100-500’WHENTotalDue<1000THEN‘500-1,000’WHENTotalDue<2500THEN‘1,000-2,500’WHENTotalDue<5000THEN‘2,500-5,000’WHENTotalDue<10000THEN‘5,000-10,000’WHENTotalDue<50000THEN‘10,000-50,000’WHENTotalDue<100000THEN‘50,000-100,000’ELSE‘>100,000’END,Orders=COUNT(*)

Page 183: REAL SQL QUERIES

FROMSales.SalesOrderHeaderWHEREYEAR(OrderDate)=2005GROUPBYCASEWHENTotalDue<100THEN1WHENTotalDue<500THEN2WHENTotalDue<1000THEN3WHENTotalDue<2500THEN4WHENTotalDue<5000THEN5WHENTotalDue<10000THEN6WHENTotalDue<50000THEN7WHENTotalDue<100000THEN8ELSE9END,CASEWHENTotalDue<100THEN‘0-100’WHENTotalDue<500THEN‘100-500’WHENTotalDue<1000THEN‘500-1,000’WHENTotalDue<2500THEN‘1,000-2,500’WHENTotalDue<5000THEN‘2,500-5,000’WHENTotalDue<10000THEN‘5,000-10,000’WHENTotalDue<50000THEN‘10,000-50,000’WHENTotalDue<100000THEN‘50,000-100,000’ELSE‘>100,000’ENDORDERBYSortID

Page 184: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION41:E-MAILMYSTERY

SELECTN2.PersonType,AWEmail=SUM(CASEWHENN1.EmailAddressLIKE‘%adventure-works%’THEN1ELSE0END),NotAWEmail=SUM(CASEWHENN1.EmailAddressNOTLIKE‘%adventure-works%’THEN1ELSE0END),Total=COUNT(*)FROMPerson.EmailAddressN1INNERJOINPerson.PersonN2ONN1.BusinessEntityID=N2.BusinessEntityIDGROUPBYN2.PersonTypeORDERBYTotalDESC

Page 185: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION42:THEMENTORS

WITHSalesGroupingAS(SELECTSalesPersonID,SalesTotal=SUM(SubTotal),SalesRankSubTotalDESC=ROW_NUMBER()OVER(ORDERBYSUM(Subtotal)DESC),SalesRankSubTotalASC=ROW_NUMBER()OVER(ORDERBYSUM(Subtotal))FROMSales.SalesOrderHeaderWHEREYEAR(OrderDate)=2008ANDSalesPersonIDISNOTNULLGROUPBYSalesPersonID)

SELECTTOP5SuccessSalesPersonID=N1.SalesPersonID,SuccessRevenue=N1.SalesTotal,UnsuccessSalesPersonID=N2.SalesPersonID,UnsuccessRevenue=N2.SalesTotalFROMSalesGroupingN1INNERJOINSalesGroupingN2ONN1.SalesRankSubTotalDESC=N2.SalesRankSubTotalASCORDERBYN1.SalesRankSubTotalDESC

Page 186: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION43:CALENDAROFWORKDAYS

—DROPTABLEHumanResources.Calendar

CREATETABLEHumanResources.Calendar(DateIDINT,[Date]DATETIME,[Year]INT,TextMonthVARCHAR(50),DateMonthDATETIME,[DayOfWeek]VARCHAR(50),IsBusinessDayTINYINT)

DECLARE@StartDateDATETIME=‘1990-01-01’DECLARE@EndDateDATETIME=‘2015-01-01’

DECLARE@TotalDaysINT=DATEDIFF(DAY,@StartDate,@EndDate)+1

DECLARE@IndexINT=1

WHILE@Index<[email protected](DateID)SELECT@IndexSET@Index=@Index+1END

UPDATEN1SET[Date]=DATEADD(DAY,DateID-1,@StartDate)FROMHumanResources.CalendarN1

UPDATEN1SET[Year]=YEAR([Date]),TextMonth=DATENAME(MONTH,[Date])+‘‘+DATENAME(YEAR,[Date])

Page 187: REAL SQL QUERIES

,DateMonth=DATEADD(MONTH,DATEDIFF(MONTH,0,[Date]),0),[DayOfWeek]=DATENAME(DW,[Date]),IsBusinessDay=CASEWHENDATENAME(DW,[Date])IN(‘Saturday’,‘Sunday’)THEN0ELSE1ENDFROMHumanResources.CalendarN1

SELECT[Year],BusinessDays=SUM(IsBusinessDay)FROMHumanResources.CalendarGROUPBY[Year]ORDERBY[Year]

Page 188: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION44:ANNUALSALARIESBYEMPLOYEE

—DROPTABLE#EmployeePayHistory

SELECT*,BusinessEntityOrder=ROW_NUMBER()OVER(PARTITIONBYBusinessEntityIDORDERBYRateChangeDate),RateEndDate=CONVERT(DATETIME,NULL),BusinessDays=CONVERT(INT,NULL)INTO#EmployeePayHistoryFROMHumanResources.EmployeePayHistory

UPDATEN1SETRateEndDate=(SELECTTOP1RateChangeDateFROM#EmployeePayHistoryX1WHEREN1.BusinessEntityID=X1.BusinessEntityIDANDX1.BusinessEntityOrder=N1.BusinessEntityOrder+1ORDERBYX1.RateChangeDate)FROM#EmployeePayHistoryN1

UPDATEN1SETBusinessDays=(SELECTCOUNT(*)FROMHumanResources.CalendarX1WHEREX1.[Date]BETWEENN1.RateChangeDateANDISNULL(N1.RateEndDate,‘2009-01-01’)ANDX1.IsBusinessDay=1)FROM#EmployeePayHistoryN1

—DROPTABLE#EmployeePayCalendar

SELECT*,DailyPay=Rate*8INTO#EmployeePayCalendarFROM#EmployeePayHistoryN1INNERJOINHumanResources.CalendarN2ONN2.[Date]>=N1.RateChangeDateANDN2.[Date]<ISNULL(N1.RateEndDate,‘2009-01-01’)

Page 189: REAL SQL QUERIES

ANDN2.IsBusinessDay=1

SELECTBusinessEntityID,WorkingYear=[Year],TotalPay=SUM(DailyPay)FROM#EmployeePayCalendarWHERE[Year]BETWEEN2005AND2008GROUPBYBusinessEntityID,[Year]ORDERBYBusinessEntityID,[Year]

Page 190: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION45:ANNUALSALARIESBYDEPARTMENT

—DROPTABLE#EmployeePayDepartmentCalendar

SELECTN1.DepartmentID,N1.StartDate,N1.EndDate,N2.*INTO#EmployeePayDepartmentCalendarFROMHumanResources.EmployeeDepartmentHistoryN1LEFTJOIN#EmployeePayCalendarN2ONN1.BusinessEntityID=N2.BusinessEntityIDANDN2.[Date]BETWEENN1.StartDateANDISNULL(N1.EndDate,‘2009-01-01’)

—DROPTABLE#DepartmentEmployeeSummary

SELECTDepartmentID,BusinessEntityID,TotalPay=SUM(DailyPay)INTO#DepartmentEmployeeSummaryFROM#EmployeePayDepartmentCalendarWHERE[Year]=2008GROUPBYDepartmentID,BusinessEntityID

SELECTDepartmentID,MinSalary=MIN(TotalPay),AvgSalary=AVG(TotalPay),MaxSalary=MAX(TotalPay)FROM#DepartmentEmployeeSummaryGROUPBYDepartmentID

Page 191: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION46:HOLIDAYBONUS

SELECTN1.BusinessEntityID,N2.FirstName,N2.LastName,N1.JobTitle,Bonus=(SELECTTOP1RateFROMHumanResources.EmployeePayHistoryX1WHEREN1.BusinessEntityID=X1.BusinessEntityIDORDERBYRateChangeDateDESC)*50FROMHumanResources.EmployeeN1INNERJOINPerson.PersonN2ONN1.BusinessEntityID=N2.BusinessEntityIDWHEREN1.SalariedFlag=1ORDERBYN1.BusinessEntityID

Page 192: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION47:COMPANYPICNIC

SELECTN1.BusinessEntityID,FullName=CONVERT(VARCHAR(50),FirstName)+‘‘+CONVERT(VARCHAR(50),LastName)+ISNULL(‘,‘+Suffix,”),Dept=N4.NameFROMPerson.PersonN1INNERJOIN(SELECTBusinessEntityID,MaxStart=MAX(StartDate)FROMHumanResources.EmployeeDepartmentHistoryGROUPBYBusinessEntityID)N2ONN1.BusinessEntityID=N2.BusinessEntityIDINNERJOINHumanResources.EmployeeDepartmentHistoryN3ONN2.MaxStart=N3.StartDateANDN2.BusinessEntityID=N3.BusinessEntityIDINNERJOINHumanResources.DepartmentN4ONN3.DepartmentID=N4.DepartmentIDWHEREN1.PersonTypeIN(‘SP’,‘EM’)ORDERBYDept,FullName

Page 193: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION48:SALESQUOTACHANGES

SELECTDISTINCTN1.BusinessEntityID,SalesRepLastName=N4.LastName,Yr2006StartQuota=N2.SalesQuota,Yr2007EndQuota=N3.SalesQuota,[%ChangeQuota]=(N3.SalesQuota-N2.SalesQuota)/N2.SalesQuota*100FROMSales.SalesPersonQuotaHistoryN1INNERJOINSales.SalesPersonQuotaHistoryN2ONN1.BusinessEntityID=N2.BusinessEntityIDANDN2.QuotaDate=(SELECTMIN(QuotaDate)FROMSales.SalesPersonQuotaHistoryWHEREYEAR(QuotaDate)=2006)INNERJOINSales.SalesPersonQuotaHistoryN3ONN1.BusinessEntityID=N3.BusinessEntityIDANDN3.QuotaDate=(SELECTMAX(QuotaDate)FROMSales.SalesPersonQuotaHistoryWHEREYEAR(QuotaDate)=2007)INNERJOINPerson.PersonASN4ONN1.BusinessEntityID=N4.BusinessEntityID

Page 194: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION49:SCRAPRATE

—DROPVIEWProduction.Vw_ScrapRates

CREATEVIEWProduction.Vw_ScrapRates

AS

SELECTTOP10PERCENTN1.WorkOrderID,DueDate=CAST(N1.DueDateASDATE),ProdName=N3.Name,ScrapReason=N2.Name,N1.ScrappedQty,N1.OrderQty,[PercScrapped]=ROUND(N1.ScrappedQty/CONVERT(FLOAT,N1.OrderQty)*100,2)FROMProduction.WorkOrderN1INNERJOINProduction.ScrapReasonN2ONN1.ScrapReasonID=N2.ScrapReasonIDINNERJOINProduction.ProductN3ONN1.ProductID=N3.ProductIDWHEREN1.ScrappedQty/CONVERT(FLOAT,N1.OrderQty)>0.03ORDERBYN1.DueDateDESC

Page 195: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION50:REASONS

WITHReasonsAS(SELECTN1.SalesOrderID,ReasonName=N2.Name,ReasonInfluence=CASEWHENCOUNT(N3.SalesOrderID)>1THEN‘ContributingReason’WHENCOUNT(N3.SalesOrderID)=1THEN‘ExclusiveReason’ENDFROMSales.SalesOrderHeaderSalesReasonN1INNERJOINSales.SalesReasonN2ONN1.SalesReasonID=N2.SalesReasonIDINNERJOINSales.SalesOrderHeaderSalesReasonN3ONN1.SalesOrderID=N3.SalesOrderIDGROUPBYN1.SalesOrderID,N2.Name)

SELECTReasonName,ReasonInfluence,SalesOrderCount=COUNT(*)FROMReasonsGROUPBYReasonName,ReasonInfluenceORDERBYReasonName,SalesOrderCountDESC

Page 196: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION51:EXCESSINVENTORY

—PartISELECTSpecialOfferID,DiscountType=[Type],DiscountDescr=[Description],Category,StartDate,EndDate,DiscountPctFROMSales.SpecialOfferWHERE[Type]=‘ExcessInventory’

—PartII

SELECTN1.SpecialOfferID,DiscountType=[Type],DiscountDescr=[Description],N1.Category,N1.StartDate,N1.EndDate,N1.DiscountPct,SalesOrders=(SELECTCOUNT(DISTINCTX1.SalesOrderID)FROMSales.SalesOrderDetailX1WHEREN1.SpecialOfferID=X1.SpecialOfferID)FROMSales.SpecialOfferN1WHEREN1.[Type]=‘ExcessInventory’

Page 197: REAL SQL QUERIES

SOLUTIONTOCHALLENGEQUESTION52:PAYRATECHANGES

WITHDataAS(SELECTBusinessEntityID,PayRateNumber=ROW_NUMBER()OVER(PARTITIONBYBusinessEntityIDORDERBYRateChangeDateDESC),RateChangeDate,RateFROMHumanResources.EmployeePayHistory)

SELECTN1.BusinessEntityID,RatePrior=N2.Rate,LatestRate=N1.Rate,PercentChange=CONVERT(VARCHAR(10),(N1.Rate-N2.Rate)/N2.Rate*100)+‘%’FROMDataN1LEFTJOINDataN2ONN1.BusinessEntityID=N2.BusinessEntityIDANDN2.PayRateNumber=2WHEREN1.PayRateNumber=1