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

Tài liệu MASTERING SQL SERVER 2000- P22 ppt

50 304 0
Tài liệu đã được kiểm tra trùng lặp

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

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Analysis Services
Trường học University of Information Technology
Chuyên ngành Information Technology
Thể loại Bài giảng
Năm xuất bản 2000
Thành phố Ho Chi Minh City
Định dạng
Số trang 50
Dung lượng 1,55 MB

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

Nội dung

CUBE and ROLLUP QueriesFor quick cube analysis of data stored on SQL Server, you can use the CUBE andROLLUP operators in a SELECT statement: SELECT GROUP BY expression WITH CUBE SELECT

Trang 1

FIGURE 28.15

Selecting training data

in the Mining Model

Wizard

Click Next to move to the Create Dimension and Virtual Cube panel This panelallows you to capture the results of the data-mining process for further analysis Inthis example, you’ll name the dimension Customer Analysis and the virtual cubeMined Cube A virtual cube, you’ll recall, is a cube that contains information fromother cubes—in this case, the Sales_1998 cube and the mined data

Click Next to move to the finish panel of the Mining Model Wizard Here youmust assign a name to the model You’ll choose Customer Analysis Model as a name.Select Save and Process Now, and click Finish to create the data-mining model.After the model has been processed, you can right-click it in Analysis Managerand choose Browse to see the results of the analysis Figure 28.16 shows a data-mining model open in the Data Mining Model Browser The different shadings used

in the model indicate how strongly the input data correlates with the factor beingpredicted Analysis Services automatically arranges factors to show you the most sig-nificant ones first In this particular model, whether the customer had better than apartial high school education is the most significant factor in predicting yearlyincome You can use the Content Navigator in the upper-right-hand corner of theBrowser to drill down to increasingly less important factors

Trang 2

FIGURE 28.16

Browsing a data-mining model

OLAP from the Client

So far, all of the OLAP we’ve looked at has been done directly at a server runningMicrosoft SQL Server Analysis Services However, there are alternatives that willretrieve OLAP information from a client In this section, we’ll show you two of thesealternatives The first is an older technique that doesn’t use Analysis Services at all:

T-SQL includes two operators, CUBE and ROLLUP, that let you perform some OLAPanalysis without any software beyond SQL Server itself The second technique we’lldemonstrate is that of using Microsoft Excel as a way to browse data that’s stored inAnalysis Services cubes

OLAP FROM THE CLIENT

P A R T

VI

Trang 3

CUBE and ROLLUP Queries

For quick cube analysis of data stored on SQL Server, you can use the CUBE andROLLUP operators in a SELECT statement:

SELECT <select clauses>

GROUP BY expression WITH CUBE

SELECT <select clauses>

GROUP BY expression WITH ROLLUP

Either CUBE or ROLLUP can be used with the full spectrum of clauses in theSELECT statement that you saw in Chapter 6: FROM, WHERE, ORDER BY, and so on.The exception to this rule is that you can’t use DISTINCT with an aggregate clause andeither CUBE or ROLLUP If you include, for example, COUNT(DISTINCT CustomerID)and CUBE in the same SQL statement, SQL Server will return an error message.CUBE and ROLLUP can be used only as part of a GROUP BY clause They add addi-tional rows to the result set beyond those normally generated by the GROUP BYclause If you specify WITH CUBE as part of a GROUP BY clause, each possible group-ing level is summarized in all possible combinations If you specify WITH ROLLUP in

a GROUP BY clause, a hierarchical set of summary rows is introduced

Some examples will make this clear First, consider this query (performed on datafrom the Northwind sample database) without CUBE or ROLLUP:

SELECT OrderDate, ShipCountry, EmployeeID, COUNT(OrderID) AS TotalOrders FROM Orders GROUP BY OrderDate, ShipCountry, EmployeeIDORDER BY OrderDate, ShipCountry, EmployeeIDFigure 28.17 shows the results of running this query in SQL Server Query Analyzer.Each row in the result comes directly from taking one combination of the GROUP BYfields For example, the first row shows that there was one order on July 4th shipped

to France taken by employee number 5

Trang 4

FIGURE 28.17

Simple GROUP BY

query

If you add the WITH CUBE operator to this query, the SQL changes only slightly:

SELECT OrderDate, ShipCountry, EmployeeID, COUNT(OrderID) AS TotalOrders FROM Orders GROUP BY OrderDate, ShipCountry, EmployeeID WITH CUBEORDER BY OrderDate, ShipCountry, EmployeeID

Figure 28.18 shows the results of this new SELECT statement The first row of theseresults shows that there are 830 total orders The second shows that 123 were taken

by employee number 1 Row 11 in the result set shows that 16 orders were shipped toArgentina Note that the NULL values can appear in any column of a WITH CUBEquery WITH CUBE summarizes the results along all possible axes

OLAP FROM THE CLIENT

P A R T

VI

Trang 5

FIGURE 28.18

GROUP BY WITH CUBE

On the other hand, you can also add the WITH ROLLUP operator to the originalquery:

SELECT OrderDate, ShipCountry, EmployeeID, COUNT(OrderID) AS TotalOrders FROM Orders GROUP BY OrderDate, ShipCountry, EmployeeID WITH ROLLUP

ORDER BY OrderDate, ShipCountry, EmployeeIDThe results of this final query are shown in Figure 28.19 In this query, the loca-tions of the NULL values are constrained to be at the end of the hierarchy of ROLLUPcolumns For example, you can have a NULL in EmployeeID alone, or in ShipCountryand EmployeeID, but not in ShipCountry alone A WITH ROLLUP query is most use-ful for providing the information necessary for a report with subtotals, rather thanthe multidimensional analysis of a WITH CUBE query or a true cube produced with

Trang 6

FIGURE 28.19

GROUP BY WITH ROLLUP

Using Excel to Retrieve Data from Analysis Services

You can also use the full power of Analysis Services from client applications This ismade possible by the Microsoft PivotTable Service, a client-side implementation ofAnalysis Services The PivotTable Service is included with Microsoft Excel 2000

New in SQL Server 2000 Analysis Services is the ability to connect the PivotTableService to an analysis server using HTTP as the protocol—that is, to use the Internet toretrieve data from an analysis server In this section, we’ll show you how to set this upand display information on a client across the Internet

First, you need to set up some prerequisites:

1 Internet Information Server must be running on the same computer as the

analysis server

2 You need to copy the msolap.asp file, installed by Analysis Services in the Program

OLAP FROM THE CLIENT

P A R T

VI

Trang 7

3 You must install the SQL Server 2000 Client Tools on the computer where you

will design and display the Excel worksheet

Then, to display data from a remote analysis server on an Excel 2000 worksheet viaHTTP, follow these steps:

1 Launch Microsoft Excel 2000 with a new, blank worksheet.

2 Select Data ➣ PivotTable and PivotChart Report This will launch the PivotTable

and PivotChart Report Wizard

3 Select External Data Source as the source of the data Click Next.

4 Click Get Data to open the Choose Data Source dialog box.

5 Select the OLAP Cubes tab of the Choose Data Source dialog box

6 Select <New Data Source> and click OK.

7 Assign a name to your new data source

8 Select Microsoft OLE DB Provider for OLAP Services 8.0 as the OLE DB provider

to use Be sure to select the provider with the 8.0 version number

9 Click Connect to open the Multidimensional Connection dialog box, shown in

Figure 28.20 Enter the Web address of the computer that’s running Analysis

Ser-vices You can use either the http://servername form or the http://IP Address

form of the server address You don’t need to enter authentication information ifthe Internet Information Server accepts anonymous connections

FIGURE 28.20

Multidimensional Connection dialog box

Trang 8

10 Click Next Select the Analysis Services database that contains the cube with the

information that you wish to display and click Finish

11 Select the cube that you wish to display and click OK twice to return to the

PivotTable and PivotChart Wizard

12 Click Next, select a location for the PivotTable, and click Finish.

The result of this process will be an Excel PivotTable that’s connected to a cube on

the analysis server via the HTTP protocol You can drag fields from the PivotTable field

well (the list of fields on the PivotTable toolbar) to the worksheet to define the display

of the cube, just as if the data had originated in Microsoft Excel Figure 28.21 shows aPivotTable based on an Analysis Services cube

OLAP FROM THE CLIENT

P A R T

VI

Trang 9

You learned the basic terminology of OLAP and saw how to use Analysis Services toextract aggregate information from a large amount of data You also saw how AnalysisServices performs data mining and learned how to display OLAP results in clientapplications.

In the next chapter, we’ll introduce another product that ships as part of the SQLServer 2000 package: Microsoft English Query, which allows you to pose questions ineveryday language instead of the formal language of T-SQL

Trang 10

CHAPTER 29

Microsoft English Query

F E A T U R I N G : What Is English Query? 1080 English Query Components 1081 Creating an English Query

Deploying an English Query

Trang 11

O ne of the problems that end users have with SQL Server is the need to use

the T-SQL language when asking for information from a database Manyhours of development effort have been invested in coming up with inter-faces to hide the details of this process from the users SQL Server 2000includes a tool named Microsoft English Query (completely overhauled from the tool

of the same name that was shipped as part of SQL Server 7) that’s designed to makeinteracting with databases simpler By creating an English Query application, you canmake it possible for your end users to extract information from a database by usingplain English instead of SQL queries

In this chapter, we’ll explain the basic concepts of English Query and show howyou can use it to enable natural language querying for a database

What Is English Query?

English Query is a tool that builds specialized applications based on a relational

data-base (the datadata-base may be stored on either SQL Server or Oracle) These applicationsallow the user to pose questions in plain English instead of in SQL For example,instead of submitting the query

SELECT * FROM Customers WHERE State = ‘Vermont’

an English Query user would just type the questionWho are the Customers in Vermont?

Of course, English Query isn’t magic English Query applications are constructed inthe Model Editor, a tool that’s hosted in the familiar Visual Studio shell This mayindicate that future versions of Visual Studio will ship with English Query, althoughMicrosoft has made no announcement to that effect yet The Model Editor includesWizards that do most of the work of building an application based on reasonableassumptions It’s your job as developer to fine-tune the results

Once your English Query model is complete, you use the Model Editor to create acompiled version of the model This compiled version can be used together with theEnglish Query runtime files and (of course) the original database to answer the user’squestions The compiled model can be accessed in a variety of ways, including from adedicated application written in a language such as Visual Basic or from a set of Webpages Later in this chapter, you’ll see how to deploy an English Query application to

an IIS-based Web site

Trang 12

language interface to an OLAP model We won’t cover this advanced capability in thisbook For more information, refer to the English Query help file under the heading “Analy-sis Services in English Query.”

English Query Components

English Query consists of a number of interrelated components These include:

• The English Query model, which captures the semantic information from yourdatabase in a form that English Query can understand

• The Question Builder, a control that lets you integrate English Query into otherapplications

• The English Query runtime, a set of files that you can redistribute when youneed to make use of English Query

In this section, we’ll briefly describe each of these components

English Query Models

There is a great deal of knowledge about the English language already built into lish Query For example, it knows that customers buy items and that employees workfor companies However, what it doesn’t know is how these concepts connect withyour database: whether there are customers, items, employees, and companies in yourdatabase and, if so, where they are stored The job of an English Query model is tocapture the structure of your database in a form that makes it useful to English Query

Eng-An English Query model consists of both database objects and semantic objects

Database objects are the familiar schema objects from your SQL Server (or Oracle)

data-base: tables, fields, joins, datatypes, keys, and so on Semantic objects hold information

that connects these database objects with English Query’s knowledge of the language

There are three main types of semantic object:

Entity: An entity is a noun represented by a database object This might be a

person such as a customer, a place such as a city, a thing such as an inventoryitem, or an idea such as a schedule Entities typically map directly to tables andfields

ENGLISH QUERY COMPONENTS

P A R T

VI

Trang 13

Relationship: A relationship is a phrase expressing the connection between two entities For example, customers purchase tickets would express the relationship

between customer entities and ticket entities

Phrasing: A phrasing is a way of expressing a relationship in English A single relationship might give rise to multiple phrasings For example, customers

purchase tickets and tickets are sold to customers are two phrasings for the same

relationship The more phrasings you include in your English Query model, the better that model will be at answering questions phrased in English

Question Builder

The Question Builder is an ActiveX control that can be used to integrate an EnglishQuery application with any ActiveX host language: Visual Basic, Visual C++, ASPpages, and so on The Question Builder is new in the version of English Query that’sshipped with SQL Server 2000 and is designed to help users determine the types ofquestions that they can ask an English Query application

Figure 29.1 shows the Question Builder in action (here connected to an applicationbased on the Northwind sample database) The leftmost pane of the Question Builderlists all of the entities and relationships in the current English Query model The cen-ter pane is a drag-and-drop target The user can drag entities and drop them here tosee the relationships between those entities The rightmost pane suggests typicalquestions that can be answered using the selected entities

Trang 14

FIGURE 29.2

Asking questions about

a particular order

The English Query Runtime

Depending on how you deploy your English Query application, you may need toredistribute the English Query runtime files If you’re shipping a standalone EnglishQuery application written in C++, Visual Basic, or another programming language,you need to make sure that all of the users of the application have these librariesinstalled:

Regsvr32 Mseqole.dll

If you’re using a Web server for deploying your application, those libraries need to

be installed only on the Web server

ENGLISH QUERY COMPONENTS

P A R T

VI

Trang 15

If your application uses the Question Builder, you also need to make sure yourusers have the appropriate ActiveX control installed For stand-alone applications,you can install and register Mseqgrqb.ocx to deliver this control For Web applica-tions, you should include Mseqgrqb.cab in the Web application This file containsthe ActiveX control and the help file, and will automatically be downloaded by theuser’s browser when they load a page that uses the control.

WARNING You must make sure that every user of an English Query application has

a SQL Server client access license

Creating an English Query Application

In this section, we’ll walk through the process of creating a typical English Queryapplication, using the Northwind sample database from SQL Server 2000 as theunderlying database We’ll cover five steps in this process:

1 Preparing the database for English Query

2 Creating an English Query project

3 Adding synonyms to the English Query model

4 Adding relationships to the English Query model

5 Testing the application

Each of these steps is covered in more detail in the remainder of this section

Preparing Your Database for English Query

Although you can use English Query to develop a natural language interface for anySQL Server or Oracle database, you’ll get the best results from the English Query Wiz-ards if you put some effort into preparing your database before running the Wizards

To get the best results from English Query, you need to make sure your database isproperly normalized (refer to Chapter 4 if you need a refresher on normalization) Inparticular, you should check these points:

• Is each entity represented as only one row in a table?

• Does each column remain constant in meaning throughout each table?

• Does each table represent only one entity?

Trang 16

• Are individual entities represented as individual rows rather than columns?

• Are individual entities represented as individual rows rather than tables?

• Do all joins use equality between primary and foreign keys?

• Are tables joined with primary and foreign keys?

If there are problems with your database from the standpoint of English Query,there are two ways that you can proceed First, you can renormalize your tables sothat they meet the requirements of English Query Alternatively, you can create nor-malized views and base the English Query application on the views rather than thebase tables

Let’s look at each of these potential problems in a bit more detail

Each Entity a Single Row

Sometimes it’s tempting to store multiple rows referring to different states of the sameentity in a single table For example, you might define a table of inventory that storesinformation on both quantity on hand and quantity on order, as shown in Table 29.1

In this case, the State column contains the value H for quantity on hand or O forquantity on order

TABLE 29.1: MULTIPLE ROWS FOR A SINGLE ENTITY

InventoryItem State Quantity

CREATE VIEW CurrentInventoryAS

SELECT InventoryItem, QuantityFROM Inventory

Trang 17

CREATE VIEW InventoryOnOrderAS

SELECT InventoryItem, QuantityFROM Inventory

WHERE State = ‘O’

With this redefinition, English Query can understand both CurrentInventory andInventoryOnOrder as separate entities

Each Field Constant in Meaning

A similar issue to storing multiple entities in a single table is using codes within a singlecolumn to store information For example, the Inventory table shown in Table 29.2 usesthe convention that a positive quantity represents inventory on hand, while a negativequantity represents a quantity on order

TABLE 29.2: TABLE THAT USES CODING WITHIN A COLUMN TO VARY MEANING

InventoryItem Quantity

To make this scheme intelligible to English Query, you can once again create a pair

of views to break out the two different types of information stored in the Quantitycolumn:

CREATE VIEW InventoryOnHandAS

SELECT InventoryItem, Quantity FROM Inventory

Trang 18

One Entity per Table

Sometimes database designers attempt to cut down on the number of tables in a base by lumping multiple entities into a single table For example, consider the table

data-of vehicles shown in Table 29.3

TABLE 29.3: MULTIPLE ENTITIES IN A SINGLE TABLE

VehicleID VehicleType Wingspan IsConvertible

CREATE VIEW PlanesAS

SELECT VehicleID, VehicleType, WingspanFROM Vehicles

WHERE VehicleType = ‘Plane’

CREATE VIEW CarsAS

SELECT VehicleID, VehicleType, IsConvertibleFROM Vehicles

WHERE VehicleType = ‘Car’

Entities in Rows Rather Than Columns

A common mistake in database design is to use repeating columns in a table

Table 29.4 shows an example of this problem

CREATING AN ENGLISH QUERY APPLICATION

P A R T

VI

Trang 19

TABLE 29.4: REPEATING COLUMNS IN A TABLE

OrderID ItemID1 ItemID2 ItemID3

You can solve this problem by using a union query to change the multiplecolumns to multiple rows:

CREATE VIEW OrderRowsAS

SELECT OrderID, ItemID1FROM OrderItems

UNIONSELECT OrderID, ItemID2FROM OrderItems

UNIONSELECT OrderID, ItemID3 FROM OrderItems

Entities in Rows Rather Than Tables

You may also run across a database that stores the same entity in multiple tables cally this is the case when older information is saved in an archival table For example,you might have a database that contains the two tables shown in Tables 29.5 and 29.6

Typi-TABLE 29.5: CURRENT ORDERING Typi-TABLE

Item TotalQuantity

Trang 20

CREATE TABLE OrderQuantitiesAS

SELECT Item, TotalQuantityFROM CurrentOrderQuantitiesUNION

SELECT Item, TotalQuantity1999FROM HistoricOrderQuantities

All Joins Should Use Equality

Another issue that can cause a problem for English Query is a bit more obscure SQLServer supports the use of nonstandard joins between tables That is, you can join twotables with operators such as < or >=, in addition to joining the tables with strictequality English Query doesn’t know what to do with such a join, and you must use aview to translate it to a standard join using equality This condition is rarely encoun-tered in practice, though

Joins Should Be Made Explicit

Sometimes databases do not have explicit primary- and foreign-key relationshipsbetween tables This is often the case, for example, in older databases that have beenmigrated to SQL Server 2000 If this is the case in your database, you should consideradding primary- and foreign-key information to your tables before creating yourEnglish Query project This will allow English Query to answer questions involvingmultiple tables, instead of only questions involving a single table

Figure 29.3 shows a database diagram for the Northwind sample database with theaddition of explicit joins between tables This is the version that we’ll use for our sampleproject in this chapter

CREATING AN ENGLISH QUERY APPLICATION

P A R T

VI

Trang 21

it manually by choosing File ➢ New Project.

TI P If you can’t find English Query on the Start menu, check to make sure that it wasinstalled on your computer Installing English Query requires running a separate setup pro-gram after the main SQL Server installation is complete

Trang 22

The Wizard will open with the familiar OLE DB Data Link Properties dialog box.

Here you should select the appropriate OLE DB provider and database for your English Query project In this chapter, we’ll use the SQL Server provider to access acopy of the Northwind sample database After selecting the database, click OK tolaunch the Wizard itself

The SQL Project Wizard uses only two panes (and it doesn’t use the familiarNext/Back/Finish Wizard interface) In the first pane, you select the tables and viewsthat you would like to use in your English Query project All nonsystem tables andviews in your database will be available In our sample, we’ve chosen to include all ofthe tables from the Northwind database in the project

When you click OK after selecting tables, English Query will retrieve schema mation from your database for each of the selected tables The Project Wizard willthen display the proposed entities and relationships that it will create, as shown inFigure 29.5

infor-CREATING AN ENGLISH QUERY APPLICATION

P A R T

VI

Trang 23

FIGURE 29.5

Entities and relationships in the Project Wizard

Generally, the Project Wizard will propose an entity for each table in the databasethat you’ve chosen to include You can determine which of these entities the ProjectWizard will actually create by selecting or deselecting the checkbox to the left of theentity name You can also click the + signs to expand the entity and see a list of rela-tionships (the category entity is expanded in Figure 29.5) As you can see, the ProjectWizard uses a number of rules to determine possible relationships:

• Columns are used to generate have or are in relationships.

• Related tables are used to generate have relationships.

• Some special column names are recognized by the Wizard For example, the egory_name column is recognized as being the name of the entity

cat-You can click the icons indicating entities or relationships to view additionaldetails Once you’ve chosen which entities and relationships to use in your model,click OK to proceed The Project Wizard will generate your English Query project andopen it in the main English Query interface, as shown in Figure 29.6

Trang 24

FIGURE 29.6

New project in English Query

English Query inherits all of the windows and controls of the Visual Studio shell inthis release of SQL Server However, you’ll find that English Query is not an excep-tionally good fit in this shell, and you can simply ignore most of the windows (in thefuture, you may well include an English Query project in a larger Visual Studio solu-tion, of course, which makes the rest of this interface more useful) Here’s what you’llsee when you open an English Query project:

• The Document Outline window is not used with English Query projects Wesuggest closing this window

• The Task List window lets you keep a to-do list that’s saved as a part of your lish Query project If you have some other means of keeping track of tasks, youshould close this window as well

Eng-• The Project Explorer shows you all of the files that are a part of your EnglishQuery project Usually you won’t need this information

• The Data View window shows the database connection that your English Queryproject is using to retrieve data This is normally also extraneous information

CREATING AN ENGLISH QUERY APPLICATION

P A R T

VI

Trang 25

• The Semantics tab in the main document window shows the English Queryentities and relationships that are a part of your project, and provides you with

a way to create new relationships This is where you’ll do most of your work

• The SQL tab in the main document window shows the database objects that areused in your English Query model

• If you close all of the extraneous windows to get more working space, your lish Query environment will resemble that shown in Figure 29.7 If you laterdecide you want to show some of the other windows, you can reopen themfrom the View menu

Ngày đăng: 26/01/2014, 08:20

TỪ KHÓA LIÊN QUAN