Sie sind auf Seite 1von 16

MS Query (Excel 2003) Tutorial

MS Query ist eine kostengnstige und einfache Alternative fr SQL Datenauswertung, die den
Vorteil hat, dass es ohne besondere Installation, universal verwendbar ist, da die meisten
Mitarbeiter des Unternehmens Excel ohnehin verwenden. Die SQL Datenauswertung hat den
Vorteil, dass Sie mehrfache Verknpfungen auf mehreren Feldern ermglicht, die beim SVERWEIS
nur mit aufwendigen Schlsseln mglich sind. Der SVERWEIS findet immer nur den ersten Treffer.
Wenn es mehrere Treffer geben kann, dann werden diese vom SVERWEIS vorenthalten. SQL zeigt
dagegen alle Treffer an. Verknpfungen auf sehr lange Tabellen werden mit SQL viel schneller und
Arbeitsspeicher schonender ausgewertet als mit dem SVERWEIS. Im Gegensatz zu Pivot Tabellen,
werden bei SQL Auswertungen sich wiederholende Zeilenberschriften nicht ausblendet, die fr
spteres Weiterverarbeiten oder Filtern ntzlich sind.
Um die Grundlagen von MS Query zu lernen, kann das folgende Beispiel MS Query Tutorial, by
Marty Ryerson, October, 2005 benutzt werden.

The Sample Database

The mini-database that I created has three ranges organized as tables. Each of the tables has more
rows than are pictured below. I've included the images here to illustrate the data and how it's
organized. The tables are:
1. A customer table named CUST:

2. An order table named ORD:

3. A sales rep table named SREP:

Notice that like standard

Notice that like standard relational tables, these have certain fields in common.
Also notice how the second table is formatted. These formats are among the few that MS Query will
recognize. To assign these formats, choose columns B and C and then assign the first format listed
in Format, Cells, Number, Date. Then choose column F and assign the first format listed in Format,
Cells, Number, Currency.
When using Excel as the source of data, it's important that each of the tables be a named range,
because when MS Query uses workbooks as a data source it will recognize only named ranges as
tables. I usually place the ranges on separate sheets, but that isn't necessary.
Once you've set up these tables, save and close the workbook. The workbook must be closed when
it is accessed by MS Query.

Create a Connection
Open another workbook where you will create your Excel report. Choose Data, Import External
Data, New Database Query, which launches the Choose Data Source dialog box.
(If MS Query isn't installed, a message will appear asking if you want to install it. To do so, place
your installation disk in the appropriate drive and follow the on-screen instructions.)

The first time you access a database, including a workbook database, you'll need to create a new
Data Source. To do so, select the <New Data Source> line, and then click OK.
In the first edit box of the Create New Data Source dialog, give your data source a name that will
remind you what it is connected to. This is the name you will select from a list when you create
new queries later.

The item asks you to select the driver type. Because Excel is the source of data for this exercise,
select the Excel driver shown from the drop-down list.
Choose the Connect button and select the version of Excel you're working with. Notice that even if
you use Excel 2003, the most-current version of Excel listed is Excel 97-2000.

Choose the Select Workbook button, launching the Select Workbook dialog.

Use this dialog to navigate to the workbook that will serve as your data source. Here, OEDATA.xls
contains my Order Entry Data. Select the workbook from the list.
Choose OK to accept your Database Name selection. In the ODBC Microsoft Excel Setup dialog,
choose OK to return to the Create New Data Source dialog. This dialog now shows the path to your
Excel workbook that acts as your database.

Choose OK to return to the Choose Data Source dialog. Note that the Data Source you just created
is already selected in the list.

Make sure the check box at the bottom of the dialog, "Use the Query Wizard to create/edit
queries," is NOT checked. The Query Wizard can help if you are doing very simple queries, but I
want to show you more powerful features of the program. You can experiment with the Query
Wizard later, if you like.
Now that you've defined an Excel workbook as a relational database, you can use it in queries.
Create a Query
The Choose Data Source dialog now includes the data source (MSQuery--Excel) that we've defined
for the OEDATA.xls workbook. Choose OK to use this data source. This data source will appear each
time you access the Choose Data Source dialog.

After you choose OK, Excel displays both the full-screen Microsoft Query application window and
the Add Tables dialog. You will use these tools to specify what data you want returned, either by
pointing and clicking, or by pasting an SQL statement into the SQL window. For this example, we'll
use the point and click method.

In the Add Tables dialog, double-click on each of the tables you want to add. Notice that all of the
named ranges appear here.

For this example, lets add all of the tables. To do so, select each table in turn, and then choose
Add or double-click. Doing so displays them in MS Query, as shown here. After you've added each
table, close the Add Tables dialog.

The grey pane near the top of this figure is called the Tables pane. The white area at the bottom is
called the Data pane. When you execute the query, the data will be returned to a grid in the Data
The middle pane is called the Criteria pane. It isn't visible by default. To see the Criteria
pane, choose View, Criteria. You also can choose the Show/Hide Criteria button, shown here,
to toggle whether this pane is visible.
Now, lets join the tables shown in the Tables pane.
The matching field in CUST and ORD is CustNum. Click on CustNum in CUST, and drag it to
CustNum in ORD. When you drop, a line will appear, joining the two tables.
The matching field in ORD and SREP is SalID. In a similar fashion, connect the SalID field between

Now, let's use these tables to create a query.

Suppose we're interested only in sales in West Virginia. In that case, we would restrict the returned
data set to just the records where the ST (state code) field in the CUST table is equal to WV.
We set up this filter by dragging the ST field from the CUST table to the top-left cell of the Criteria
pane, and then by expressing the filter we want to use. You tell MS Query what value you want this

field to be equal to by typing the value in the second line of the criteria pane. In this case, we type
WV. (MS Query adds single quotes around WV when you move off the cell.)
On the other hand, if we wanted to show sales everywhere except West Virginia, we could enter
the expression, <> WV in this cell. This would return all records where the state code does not
have the value WV.
Please note that these criteria are not case sensitive when you query Excel files, but they might be
case sensitive when you query other data sources. For example, queries against an Oracle or SQL
Server database may be case sensitive, depending on how your database is set up.
Next, we need to tell MS Query which columns we would like to see in our Excel report. For this
exercise, let's choose to see the customer number, the customers last name, the type of customer
(cash or credit), the amount of the order, the delivery date, and the name of the sales rep. To do
this, double-click on the fields in the tables shown in the following figure, and they'll appear as
headings in the data grid.
After you've added all the fields you want, click on the Query Now button, shown here. The data
will be returned in the data grid, as shown in top few rows of this figure.

Note that the data grid isn't limited to 65,536 rows. If you suspect the dataset you've returned is
larger, you can check this by clicking on the Last Record button at the bottom of your window; it's
the right-most button shown here. Here, for example, the query produced 140 records.
Now would be a good time to save your query. This will allow you or another person to use the
same query later in a new workbook, with additional data, or both. To save the query, choose File
Save As in the Microsoft Query window and then name your query anything you want. In the File
Save As dialog you'll see two file formats, dqy and qry. If dqy is specified as the default, use that
format. The qry file format was used in earlier versions of the tool.

At this point, you may be curious to know what the SQL statement you just generated looks like.
When you click on SQL toolbar button shown here you can see the SQL statement in the SQL
window. If you know SQL, you can edit the statement to add features that are not supported by the
generator, but are supported by the ODBC driver you're using.

Export the Data to Excel

If the data in the grid is what you want to export to Excel, click on the Return Data button, shown
You'll be returned to Excel, and the Import Data window will let you decide where you want to put
the data. For this example, I'll accept the defaults, and put the data in the existing worksheet in
Column A, Row 1, by clicking the OK button.

You now can apply any formats, formulas, and so on, that you wish.

Because this is just an introduction, I will leave it at that. You can do a lot more.

You can refresh this query by clicking a button, in case the data in the original tables has

You can add formulas and have them automatically copy down each time you refresh the

You can add parameters, and have them refer to a cell in the worksheet, so that you can
see different subsets of the data.

You can generate similar queries on text files and databases. For each new data source you need to
create a Data Source Name. Once you've done so, you can use the data source repeatedly to
create any number of queries against that database. You can save the queries and use them in a
new workbook.

Return the Data to a Pivot Table

Let me show you one last trick, one that lets you analyze data when the data set you want to look
at is too big to fit on an Excel spreadsheet.
From the Data menu, select Pivot Table and Pivot Chart. Select External Data Source when the
Wizard comes up.

Choose Next.

In the "Step 2 of 3" dialog above, choose Get Data.

Choose your data source and proceed as before, or create an entirely new query. When you return,
you'll have a PivotTable with all the data in the pivot cache, but not on a spreadsheet. Even if the
data would not fit on a spreadsheet, this will allow you to create all the pivot reports you need.
The thing I find most appealing about this approach is that it is relatively easy to learn if you have
some good documentation. I have been able to reduce my workload and stress significantly by
teaching the people who want relatively simple, one-time reports, or those who want to see the
data in numerous different configurations, how to use these tools.
If you think this could be of value to you, I highly recommend Mr. Zapawas book, Excel Advanced
Report Development available now from Wiley Publishing, Inc.


MS Query 19.04.09 Marco Gruner

Neben den von Marty Ryerson beschriebenen Grundfunktionen, sind aus meiner Sicht noch
folgende Informationen wichtig:
ffnen einer Abfrage im MS Query Editors aus Excel heraus
Whle in der Namensliste der Datenbereichsnamen die Abfrage, die geffnet werden soll. Wenn der
Datenbereich markiert ist, mache auf den Bereich einen rechten Mausklick und whle Abfrage
bearbeiten. Zweimal OK klicken.

Die SQL Ausdrcke der Abfragen knnen im SQL Fenster nachbearbeitet werden. So lassen sich
mehrere Tabellen oder Abfragen mit UNION in eine Tabelle kombinieren. Es ist zum Beispiel mglich
die 65536 Zeilen Grenze von Excel zu umgehen, indem mehrere Tabellen zu einer Tabelle
kombiniert werden.


Textdatei als Datenquelle

Die 65536 Zeilen Grenze von Excel Sheets knnen eine lstige Hrde darstellen, wenn regelmig
Rohdaten auszuwerten sind, die mehr Zeilen umfassen. Es ist mglich als Datenquelle Textdateien
statt Exceldateien zu verwenden, die keiner Zeilenbegrenzung unterworfen sind.

Vorgehensweise zur Verwendung von Textdateien als Datenquelle:

Aus SAP eine DAT Datei mit .txt exportieren
Daten / Externe Daten importieren / Neue Abfrage erstellen
Neue Datenquelle / OK

Name: z.B. TextImport

Micorosoft Text Driver
Hckchen entfernen bei Aktuelles Verzeichnis verwenden
Verzeichnis auswhlen / Datei anwhlen
Format Tab
Zu scannende Zeilen z.B. 9, wenn noch viel an Header Zeilen drin sind
Vorschlagen: -> alle Spalten sollten jetzt erfasst werden, wenn nicht, dann zu scannende Zeilen
Fehler Meldung ignorieren und abbrechen

Auf dem gleichen Laufwerk wird von Excel eine schema.ini Datei erstellt.
Falls Fehlermeldungen erscheinen, dann Datei schema.ini ffnen und col1, col2, col3, etc.
(stehen ziemlich am Ende) lschen


Daten / Externe Daten importieren / Neue Abfrage erstellen
Oder Pivot mit externer Datenquelle:
Whle TextImport
Falls Zahlen als Text interpretiert werden, dann in MS Query die Texte in Zahlen umwandeln

Abfrage auf Abfrage aufbauen

Auswertungen erfordern manchmal mehrere aufeinander Aufbauende Abfragen. Um eine neue
Abfrage auf eine bestehende Abfrage aufzubauen ist es notwendig, zuerst die Abfrageergebnisse
der bestehende Abfrage an Excel zurckzugeben, womit der Bereich mit den Abfrageergebnissen
im Excel dann den Namen der bestehenden Abfrage erhlt. Anschlieend kann man die neue
Abfrage erstellen, in dem man im Query Designer sich die Daten der bestehenden Abfrage als
Tabelle einblendet.
Aus einer Absatzliste soll der Preis pro Materialnummer ermittelt werden, bei der die Menge am
hchsten ist.

Zuerst wird die Abfrage MaxMenge erstellt, die die Maximale Menge pro Materialnummer


Die Abfrage wird benannt und gespeichert und das Abfrageergebnis wird von MS Query an Excel

Im Excel entsteht ein Bereich mit Namen MaxMenge

'Max von
Material Menge'


Eine Zweite Abfrage wird erstellt, die MaxMenge mit Tab verknpft und somit die gesuchten
Preise zu der maximalen Menge findet.

Anschlieend wieder die Daten an Excel zurckgeben.

Das Ergebnis zeigt die gewnschte Ergebnisliste. Bei nderungen knnen die Ergebnisse mit Daten,
Daten aktualisieren aufgefrischt werden.


Gruppierungsfunktion fr Spalte verwenden

Rechter Mausklick auf das zu gruppierende Feld. Bei Ergebnis die Gruppierungsfunktion einstellen.

Neues berechnetes Feld in der Abfrage erstellen

Datenstze / Spalte einfgen


Verknpfungstyp (Inner Join, Right JOIN oder Left JOIN)

Mit Tabelle / Verknpfungen kann der Verknpfungstyp gewhlt werden. Der Unterschied zwischen
Inner und Right oder Left Join besteht darin, dass bei einem Inner Join in der Abfrage nur
Datenstze erzeugt werden, die in beiden Tabellen als bereinstimmende Werte vorhanden sind.
Fr den Right oder Left Join werden alle Werte der einen Tabelle verwendet und die passenden
Werte, falls vorhanden als Werte, falls nicht vorhanden als leere Felder dazugefgt.