Chapter5:AggregatingData
Wearebackwithourgrocerylist.Youcanseethatitnowhassixrowsinit,butwe
canalsoseethatweneedtobuymorethanoneofeachitem,likeourBlueberries.In
ordertodeterminethetotalnumberofitemswewillbepurchasing,wecanusewhat’s
calledanaggregatefunction.WithSQL,anaggregatefunctionisusefulforthingslike
gettingthemaximum,minimum,sumandaverage,ofvaluesinourdatabase.Inthis
example,togetthetotalnumberofitems,wewillstartwithSELECT,thenthename
oftheaggregatefunctionwewillbeusing,SUM,thenthenameofthecolumnwe
want,andthenFROM,thenameofthetableweareselectingfrom.Soyoucanseeon
therightthatthesumisfifteen,soweshouldhavefifteenitemsinourcart.
IfwechangethenumberofBlueberries,wecanseethesumincrease,inrealtime.
Wecouldeasilytryoutotheraggregatefunctionshere,becauseSumisnottheonly
one.Ifwewantedtoknowwhatisthemostthatwewillbebuyingofanyoneitem,we
coulduseMAX.Nowwhatifwewantedtomakesurewehadtherightnumberitems
aftereachaisle?WecandothatinSQLusingtheGROUPBYclause.Weaddittothe
endofaquery,specifyingthecolumnnamedGROUPBYaisle.Nowwecanseethat
inoneaislewewillhave9,inanotherwehave1.Butwedon’tactuallyknowwhich
aislewearegettingeachitemsin.WhatwecandoisjustaddAISLEtothebeginning
oftheSELECT,thereyoucanseethatwearegoingtogetnineitemsinaisle2,one
iteminaisle4,fifty-sixinaisle7andoneinaisle12.
Now,howdidthatactuallywork,behindthescenes?TheSQLenginefirstgrouped
therows(basedonaisle),thenitsummedupthequantityineachofthosegroups.
Finally,itselectedthefirstaislevaluethatitsaw,ineachgroup.Andyouknowthe
aislevalueisthesameforallofthem,sowegottheaislesbackout.Butwecouldhave
alsosaidNAMEhere,andwedoseeanameforeachoftherows,butitisabit
misleading,becauseforsomeoftheseaisles,thereareactuallymultipleitemsinthat
group.TheSQLenginejustpickedthefirstitemoutofit.Soyoureallyshouldnotbe
usingsomethingdifferentfromwhatyou’regroupingby,becauseyoumightgetan
incorrectresult.Therefore,wewillsayAISLE,andgetanaccuratepresentationofour
data.Atthispoint,you’veseenaggregatefunctions;you’veseengroupby;andnow
youcanofficiallygatherusefulstatisticsonyourdata.
ingredients 6rows
id(PK) INTEGER
name TEXT
quantity INTEGER
aisle INTEGER