1、Chapter 22:Advanced Querying and Information Retrieval陕西师范大学计算机科学学院陕西师范大学计算机科学学院数据库原理与应用课程组数据库原理与应用课程组1Chapter 22:Advanced Querying and Information RetrievalnDecision-Support SystemsqData Analysis nOLAPnExtended aggregation features in SQLqWindowing and rankingqData Mining qData Warehousing nInforma
2、tion-Retrieval Systems qIncluding Web search2Decision Support SystemsnDecision-support systems are used to make business decisions often based on data collected by on-line transaction-processing systems.nExamples of business decisions:qwhat items to stock?qWhat insurance premium to change?qWho to se
3、nd advertisements to?nExamples of data used for making decisionsqRetail sales transaction detailsqCustomer profiles(income,age,sex,etc.)3Decision-Support Systems:OverviewnData analysis tasks are simplified by specialized tools and SQL extensionsqExample tasksnFor each product category and each regio
4、n,what were the total sales in the last quarter and how do they compare with the same quarter last yearnAs above,for each product category and each customer categorynStatistical analysis packages(e.g.,:S+)can be interfaced with databasesqStatistical analysis is a large field will not study it herenD
5、ata mining seeks to discover knowledge automatically in the form of statistical rules and patterns from Large databases.nA data warehouse archives information gathered from multiple sources,and stores it under a unified schema,at a single site.qImportant for large businesses which generate data from
6、 multiple divisions,possibly at multiple sitesqData may also be purchased externally4Data Analysis and OLAPnAggregate functions summarize large volumes of datanOnline Analytical Processing(OLAP)qInteractive analysis of data,allowing data to be summarized and viewed in different ways in an online fas
7、hion(with negligible delay)nData that can be modeled as dimension attributes and measure attributes are called multidimensional data.qGiven a relation used for data analysis,we can identify some of its attributes as measure attributes,since they measure some value,and can be aggregated upon.For inst
8、ance,the attribute number of the sales relation is a measure attribute,since it measures the number of units sold.qSome of the other attributes of the relation are identified as dimension attributes,since they define the dimensions on which measure attributes,and summaries of measure attributes,are
9、viewed.5Cross Tabulation of sales by item-name and colornThe table above is an example of a cross-tabulation(cross-tab),also referred to as a pivot-table.nA cross-tab is a table where qvalues for one of the dimension attributes form the row headers,values for another dimension attribute form the col
10、umn headersnOther dimension attributes are listed on topqValues in individual cells are(aggregates of)the values of the dimension attributes that specify the cell.6Relational Representation of CrosstabsnCrosstabs can be represented as relationsnThe value all is used to represent aggregatesnThe SQL:1
11、999 standard actually uses null values in place of allnMore on this later.7Three-Dimensional Data CubenA data cube is a multidimensional generalization of a crosstabnCannot view a three-dimensional object in its entirety nbut crosstabs can be used as views on a data cube8Online Analytical Processing
12、nThe operation of changing the dimensions used in a cross-tab is called pivotingnSuppose an analyst wishes to see a cross-tab on item-name and color for a fixed value of size,for example,large,instead of the sum across all sizes.qSuch an operation is referred to as slicing.nThe operation is sometime
13、s called dicing,particularly when values for multiple dimensions are fixed.nThe operation of moving from finer-granularity data to a coarser granularity is called a rollup.nThe opposite operation-that of moving from coarser-granularity data to finer-granularity data is called a drill down.9Hierarchi
14、es on DimensionsnHierarchy on dimension attributes:lets dimensions to be viewed at different levels of detailHE.g.the dimension DateTime can be used to aggregate by hour of day,date,day of week,month,quarter or year10Cross Tabulation With HierarchynCrosstabs can be easily extended to deal with hiera
15、rchiesHCan drill down or roll up on a hierarchy11OLAP ImplementationnThe earliest OLAP systems used multidimensional arrays in memory to store data cubes,and are referred to as multidimensional OLAP(MOLAP)systems.nOLAP implementations using only relational database features are called relational OLA
16、P(ROLAP)systemsnHybrid systems,which store some summaries in memory and store the base data and other summaries in a relational database,are called hybrid OLAP(HOLAP)systems.12OLAP Implementation(Cont.)nEarly OLAP systems precomputed all possible aggregates in order to provide online responseqSpace
17、and time requirements for doing so can be very highn2n combinations of group byqIt suffices to precompute some aggregates,and compute others on demand from one of the precomputed aggregatesnCan compute aggregate on(item-name,color)from an aggregate on(item-name,color,size)qFor all but a few“non-deco
18、mposable”aggregates such as medianqis cheaper than computing it from scratch nSeveral optimizations available for computing multiple aggregatesqCan compute aggregate on(item-name,color)from an aggregate on(item-name,color,size)qCan compute aggregates on(item-name,color,size),(item-name,color)and(ite
19、m-name)using a single sorting of the base data13Extended AggregationnSQL-92 aggregation quite limitedqMany useful aggregates are either very hard or impossible to specifynData cubenComplex aggregates(median,variance)nbinary aggregates(correlation,regression curves)nranking queries(“assign each stude
20、nt a rank based on the total marks”nSQL:1999 OLAP extensions provide a variety of aggregation functions to address above limitationsqSupported by several databases,including Oracle and IBM DB214Extended Aggregation in SQL:1999nThe cube operation computes union of group bys on every subset of the spe
21、cified attributesnE.g.consider the queryselect item-name,color,size,sum(number)from salesgroup by cube(item-name,color,size)This computes the union of eight different groupings of the sales relation:(item-name,color,size),(item-name,color),(item-name,size),(color,size),(item-name),(color),(size),()w
22、here()denotes an empty group by list.nFor each grouping,the result contains the null value for attributes not present in the grouping.15Extended Aggregation(Cont.)nRelational representation of crosstab that we saw earlier,but with null in place of all,can be computed byselect item-name,color,sum(num
23、ber)from salesgroup by cube(item-name,color)nThe function grouping()can be applied on an attributeqReturns 1 if the value is a null value representing all,and returns 0 in all other cases.select item-name,color,size,sum(number),grouping(item-name)as item-name-flag,grouping(color)as color-flag,groupi
24、ng(size)as size-flag,from salesgroup by cube(item-name,color,size)nCan use the function decode()in the select clause to replace such nulls by a value such as allqE.g.replace item-name in first query by decode(grouping(item-name),1,all,item-name)16Extended Aggregation(Cont.)nThe rollup construct gene
25、rates union on every prefix of specified list of attributes nE.g.select item-name,color,size,sum(number)from salesgroup by rollup(item-name,color,size)qGenerates union of four groupings:(item-name,color,size),(item-name,color),(item-name),()nRollup can be used to generate aggregates at multiple leve
26、ls of ahierarchy.nE.g.,suppose table itemcategory(item-name,category)gives the category of each item.Then select category,item-name,sum(number)from sales,itemcategory where sales.item-name=itemcategory.item-name group by rollup(category,item-name)would give a hierarchical summary by item-name and by
27、 category.17Extended Aggregation(Cont.)nMultiple rollups and cubes can be used in a single group by clauseqEach generates set of group by lists,cross product of sets gives overall set of group by listsnE.g.,select item-name,color,size,sum(number)from sales group by rollup(item-name),rollup(color,siz
28、e)generates the groupings item-name,()X(color,size),(color),()=(item-name,color,size),(item-name,color),(item-name),(color,size),(color),()18RankingnRanking is done in conjunction with an order by specification.nGiven a relation student-marks(student-id,marks)find the rank of each student.select stu
29、dent-id,rank()over(order by marks desc)as s-rankfrom student-marksnAn extra order by clause is needed to get them in sorted orderselect student-id,rank()over(order by marks desc)as s-rankfrom student-marks order by s-ranknRanking may leave gaps:e.g.if 2 students have the same top mark,both have rank
30、 1,and the next rank is 3qdense_rank does not leave gaps,so next dense rank would be 219Ranking(Cont.)nRanking can be done within partition of the data.n“Find the rank of students within each section.”select student-id,section,rank()over(partition by section order by marks desc)as sec-rankfrom stude
31、nt-marks,student-sectionwhere student-marks.student-id=student-section.student-idorder by section,sec-ranknMultiple rank clauses can occur in a single select clausenRanking is done after applying group by clause/aggregationnExercises:qFind students with top n ranksnMany systems provide special(non-s
32、tandard)syntax for“top-n”queriesqRank students by sum of their marks in different courses ngiven relation student-course-marks(student-id,course,marks)20Ranking(Cont.)nOther ranking functions:qpercent_rank(within partition,if partitioning is done)qcume_dist(cumulative distribution)n fraction of tupl
33、es with preceding valuesqrow_number(non-deterministic in presence of duplicates)nSQL:1999 permits the user to specify nulls first or nulls last select student-id,rank()over(order by marks desc nulls last)as s-rankfrom student-marks21Ranking(Cont.)nFor a given constant n,the ranking the function ntil
34、e(n)takes the tuples in each partition in the specified order,and divides them into n buckets with qual numbers of tuples.For instance,we an sort employees by salary,and use ntile(3)to find which range(bottom third,middle third,or top third)each employee is in,and compute the total salary earned by
35、employees in each range:select threetile,sum(salary)from(select salary,ntile(3)over(order by salary)as threetilefrom employee)as sgroup by threetile22WindowingnE.g.:“Given sales values for each date,calculate for each date the average of the sales on that day,the previous day,and the next day”nSuch
36、moving average queries are used to smooth out random variations.nIn contrast to group by,the same tuple can exist in multiple windowsnWindow specification in SQL:qOrdering of tuples,size of window for each tuple,aggregate functionqE.g.given relation sales(date,value)select date,sum(value)over (order
37、 by date between rows 1 preceding and 1 following)from salesnExamples of other window specifications:qbetween rows unbounded preceding and currentqrows unbounded precedingqrange between 10 preceding and current rownAll rows with values between current row value 10 to current valueqrange interval 10
38、day precedingnNot including current row23Windowing(Cont.)nCan do windowing within partitionsnE.g.Given a relation transaction(account-number,date-time,value),where value is positive for a deposit and negative for a withdrawalq“Find total balance of each account after each transaction on the account”
39、select account-number,date-time,sum(value)over(partition by account-number order by date-timerows unbounded preceding)as balancefrom transactionorder by account-number,date-time24Data Mining25Data MiningnBroadly speaking,data mining is the process of semi-automatically analyzing large databases to f
40、ind useful patternsnLike knowledge discovery in artificial intelligence data mining discovers statistical rules and patterns nDiffers from machine learning in that it deals with large volumes of data stored primarily on disk.nSome types of knowledge discovered from a database can be represented by a
41、 set of rules.qe.g.,:“Young women with annual incomes greater than$50,000 are most likely to buy sports cars”nOther types of knowledge represented by equations,or by prediction functionsnSome manual intervention is usually requiredqPre-processing of data,choice of which type of pattern to find,postp
42、rocessing to find novel patterns26Applications of Data MiningnPrediction based on past historyqPredict if a credit card applicant poses a good credit risk,based on some attributes(income,job type,age,.)and past historyqPredict if a customer is likely to switch brand loyaltyqPredict if a customer is
43、likely to respond to“junk mail”qPredict if a pattern of phone calling card usage is likely to be fraudulentnSome examples of prediction mechanisms:qClassificationnGiven a training set consisting of items belonging to different classes,and a new item whose class is unknown,predict which class it belo
44、ngs toqRegression formulaen given a set of parameter-value to function-result mappings for an unknown function,predict the function-result for a new parameter-value27Applications of Data Mining(Cont.)nDescriptive PatternsqAssociationsnFind books that are often bought by the same customers.If a new c
45、ustomer buys one such book,suggest that he buys the others too.nOther similar applications:camera accessories,clothes,etc.qAssociations may also be used as a first step in detecting causationnE.g.association between exposure to chemical X and cancer,or new medicine and cardiac problemsqClustersnE.g.
46、typhoid cases were clustered in an area surrounding a contaminated wellnDetection of clusters remains important in detecting epidemics28Classification RulesnClassification rules help assign new objects to a set of classes.E.g.,given a new automobile insurance applicant,should he or she be classified
47、 as low risk,medium risk or high risk?nClassification rules for above example could use a variety of knowledge,such as educational level of applicant,salary of applicant,age of applicant,etc.q person P,P.degree=masters and P.income 75,000 P.credit=excellentq person P,P.degree=bachelors and (P.income
48、 25,000 and P.income 75,000)P.credit=goodnRules are not necessarily exact:there may be some misclassificationsnClassification rules can be compactly shown as a decision tree.29Decision Tree30Construction of Decision TreesnTraining set:a data sample in which the grouping for each tuple is already kno
49、wn.nConsider credit risk example:Suppose degree is chosen to partition the data at the root.qSince degree has a small number of possible values,one child is created for each value.nAt each child node of the root,further classification is done if required.Here,partitions are defined by income.q Since
50、 income is a continuous attribute,some number of intervals are chosen,and one child created for each interval.nDifferent classification algorithms use different ways of choosing which attribute to partition on at each node,and what the intervals,if any,are.nIn generalqDifferent branches of the tree