leondocu

44
Introduction To MS Query O M P U T I N G D I R E C T I O N S A U S T R A L I A

Upload: leon-zhong

Post on 11-Mar-2016

213 views

Category:

Documents


0 download

DESCRIPTION

leondocument

TRANSCRIPT

Introduction

To

MS Query

O M P U T I N G

D I R E C T I O N S

A U S T R A L I A

2

Contents Objectives ………………………………………………………….... 3 MS Query/Database Concepts …………………………………........ 4 Extracting data using Microsoft Query Wizard …………………….. 5 Extracting data without Microsoft Query Wizard ………………..… 11 Parameters ………………………………………………………….. 17 Microsoft Word Mail Merge

Example 1.Creating Labels with your spreadsheet ……….... 19 Example 2.Creating Letters with your spreadsheet ……….... 23

Creating a Mail Merge in MS Word using a MS Query ………….... 26 Inserting an Existing SQL statement …………………………….… 28 Adding other Tables/Views ………………………………………... 30 Linking your Tables/Views ………………………………….…….. 30 Joins ……………………………………………………………..…. 31 Using Finance Tables/Views ……………………………….……... 34 Example 1 using vEnrolmentDeposits …………………….………. 35 Example 2 using vCashReceiptsEntry ………………………….…. 36 MS Query Benefits/Disadvantages ………………………….…...... 37 Queries …………………………………………………….………. 37 MS Query Exercises …………………………………….………… 39 Advanced Microsoft Query & SQL Examples ……………………. 40

3

Synergetic MSQuery Introductory Training Objectives:-

At the conclusion of the course participants should:-

- Understand the benefits and disadvantages of MSQuery over other tools like Crystal Reports

- Know how Word and Excel integrate with MSQuery

- Understand the purpose of MSQuery to extract data from the database

- Recognise views and other base tables

- Understand CDA naming conventions for Views, Tables and Fields

- Know how to use the Query Wizard

- Know how not to use the Query Wizard

- Make a new Query

- Change a Query

- Copy SQL statements from a Query to email to CDA Support

- Copy SQL statements from CDA support back into the Query

- Understand the basics of an SQL Statement

4

MS Query Microsoft Query (MS Query) is a program that allows you to retrieve data from a database such as Synergetic into Microsoft Office programs such as Excel or Word.

Database Concepts

Tables store and organise the information in a database.

Views have been created by the CDA development team to make querying the database easy process. These Views contain links between several base tables for related information that could be used in similar queries. The information can be from single fields or generated formula fields. Links can be made between several Views and base tables, but sometimes the linking process can be confusing or difficult. Contact CDA if you wish to include a field in an existing view or if you require assistance with joining tables. Fields contain all of the information that is maintained in Synergetic you use any field you want in your query but it is recommended to select the fields from a View

Generated Fields can be one or more fields that have been combined and manipulated together to create another field. Eg. The MailSalutation field combines the title of a person with their surname. If this person has a spouse and the ‘Address to primary only’ is not selected within Synergetic’s Community Maintenance, their title will be joined with the partner’s. Mr and Mrs Johnson

Finding Fields in Views Knowing what fields views or tables contain is often a main hurdle when beginning a query. Two helpful Crystal reports that can be used to find fields in views or to list all the fields in a view are the following in the System module:

5

Extracting data from the Synergetic database using the Microsoft Query Wizard

In this example, MS Query wizard will be used to create a query to obtain students names and contact details. Example 1: extracting student name and contact details 1. Load Excel from your desktop 2. Click Data > Get External Data > Create New Query (Or Data > Import External

Data > New Database Query for Office XP)

3. On the Choose Data Source screen, select the SynergyOne database. Also make

sure that the ‘Use the Query Wizard to create/edit queries’ flag has been checked -> the wizard makes it easier to manipulate your query if you are a beginner.

6

4. On the SQL Server Login screen, enter your username and password

5. Scroll down the list of tables until you get to the Views, these all start with a small

‘v’. Click the ‘+’ to the left of vStudentContactAddress to list all fields that this View contains.

**Please note if SQL 2005 You will see all available tables and views including information Schema.

To filter this, select the [Options…] button and in the Owner field select dbo and [ok]

7

6. To select fields, highlight then click the ‘>’ button. If you click this button while the

View name is selected then all fields in this view will add to the Columns in your query (you very rarely need to use all fields in a view or base table).

7. Select the fields as shown in the graphic below:

When using Current Student views: FileYear – Using this allows you to set the current year to avoid using information from previous or future years. File Semester – Using this allows you to set the current semester to avoid using information from previous or future semesters.

8

The CurrentSemesterOnlyFlag can be used instead of FileYear and FileSemester.

From now on this should be used for any query that you want only data from the

current year and semester.

• Example with FileYear and FileSemester - If using the same query 3 years from

the date of creation, you will need to reset these filters to match the current year

and semester. These selections would only be useful if you want to access prior

years on the database.

• Example with CurrentSemesterOnlyFlag – You will never need to set the

FileYear and FileSemester again, this filter will allow data to ONLY be extracted

from the current semester.

AddressComma – Gets the contact’s address in and organises it in a readable, comma delimited format eg. 141 High Street, PRAHRAN VIC 3181. These fields are constructed by the system from the Address1-3, Suburb, State, PostCode and Country. They also take into account if the current person is deceased or the address is no longer valid on the system. Using StudentContactAddressFull would format each address component in a form suitable for mailing labels eg. 141 High Street PRAHAN VIC 3181 MailNamePrimary – In the format of [Contact Title] and [Contact Spouse Title] [Contact

First Initial] [Surname]. Eg. Mr P Bailey MailSalutationPrimary – This organises the format you have specified within Synergetic’s Community Maintenance. Eg. May remove the contact’s initial. Surname – This will be used for sorting purposes, you can later delete the field but keep the sorting. If you are going through the wizard then you need to add it now. NameExternal – This is the student’s [Name] [Surname] joined together. It will be used later when doing a Mail Merge within Word. If you want only the student’s preferred name then you may need to join to another table. Eg. Brian Smith. Once you finish your selections click the [Next >] button. You can also come back to this screen at any time (whilst still in the wizard) by clicking [< Back]. 8. The next step is to configure your data selections to choose the data that you want

returned to you. In nearly all cases with students and contacts you will need to set the FileYear and FileSemester to the current year and semester in your database. Set these as shown below:

9

Dropping-down the right-hand box will show you a list of all types that are used for the selected field. Note that when you choose you filter the Column Name becomes bolded, this will let you know what fields you have already applied filters to.

9. Now you need to choose a field to base the sorting of your data on. You can choose

multiple fields to sort by, but Surname is always a good option. Click the drop-down box and select Surname, leave the sort type as Ascending

Note there are two other fields you can use for sorting. If you do not use the wizard, an infinite amount of sorting and grouping can be performed.

10

10. The next screen asks you if you want to return the data to Excel or Query. For this example we will click > return the data to Excel, then click [Finish]. If you want to experiment with Query and Excel together, you can switch between them as follows:

• In Excel right-click one of the database fields then click ‘Edit Query’

• In Query click File > Return Data to Microsoft Excel 11. Now the system will gather the information that you requested from the database,

take it back to Excel and ask you where you wish to place the spreadsheet. You can position the spreadsheet wherever you want but for now, just click [OK] to the next screen.

This will place your spreadsheet starting from the first row of the first column.

12. Now, in Excel, click File > Save As… on the standard tool-bar and give your spreadsheet a name, Example1Initials.xls (Save this on your Desktop).

11

Extracting data from the Synergetic database

WITHOUT the Microsoft Query Wizard

Most of the time the Query wizard can mislead you and make it harder to manipulate your data. It is used mainly for creating quick queries but does not introduce you to the full functionality of Microsoft Query. Everything that you can do in the wizard (and more) can be done in Query itself, simply check the on-line help for any information that you require.

Starting a New Query

Example: extracting student name and contact details 1. Click Data > Get External Data > Create New Query (Or Data > Import External

Data > New Database Query for Office XP) 2. Un-check ‘Use the Query Wizard to create/edit queries’ flag.

Click [OK] then log-on to your Server.

Adding Tables

You will now jump straight into Query with an ‘Add Tables’ box displayed. If you wish for only the views to be displayed, click [Options] and un-flag all but the Views flag. (To Add another table later, go to Table > Add Tables)

12

**Please note if SQL 2005 To filter out the Information Schema Tables select ‘dbo’ in the Owner: field in the Add Tables section.

3. Scroll down the list of tables until you get to the Views, these all start with a small ‘v’. Double-click the view name ‘vStudentContactAddress’ to add the table of fields to your query. Tip: click [Options] to see the other types of tables that you could add.

4. When you have finished adding tables (in this case we are only using one View, if using multiple tables then joins need to be made, contact CDA for more information) click [Close] to continue.

Note: If you wish to remove a table, click on a field in it then press Delete on your keyboard. More tables can be added later by clicking Table > Add Tables… from the standard tool-bar.

Adding Fields from the View

There are several ways to add fields (or columns) to your spreadsheet, choose the technique that you find easiest.

5. We need to add the following fields:

ID Preferred Surname StudentYearLevel StudentContactAddressFull StudentContactMailName StudentContactMailSalutation FileYear FileSemester

a) Double-click the field from the table window as below. If you resize the table

window you’ll be able to view more of the fields.

13

b) Click & drag the field from the above window down to the spreadsheet to the

column position where you want to place it. c) Click the drop-down list on a blank column heading to display a list of all fields,

then select the field you want:

d) Click Records > Add Column, then select the field you want and give it a heading

name. Heading names of other fields can be changed by double-clicking on the heading (grey area).

To remove a field click the column heading (in grey) then press the [Delete] key on your keyboard. 6. Add a field to sort on by clicking Records > Sort, selecting the field (Surname) then

click [Add]. Multiple sort selections can be made but the fields to select from must already have been added to your spreadsheet.

14

7. Give the rows some more height & width so that you can view all information in a

large field. This is done in the same manner as an Excel spreadsheet, click-dragging the column & row dividers to make them bigger:

8. The next step is to Add Criteria (filters) to your query. Click Criteria > Add

Criteria… and the following screen will be displayed:

15

Note: Notice that when you use the drop-down for ‘Field’ here, you can choose from any field in the table you have added. In the wizard you can only choose from the fields that you add from the table.

When using Current Student views:

The CurrentSemesterOnlyFlag can be used instead of FileYear and FileSemester.

From now on this should be used for any query that you want only data from the

current year and semester.

• Example with FileYear and FileSemester - If using the same query 3 years from

the date of creation, you will need to reset these filters to match the current year

and semester. These selections would only be useful if you want to access prior

years on the database.

• Example with CurrentSemesterOnlyFlag – You will never need to set the

FileYear and FileSemester again, this filter will allow data to ONLY be extracted

from the current semester.

As with the previous example with the wizard, select fields FileYear and

FileSemester, leaving the radio button set to And, and after each clicking [Add]. In other cases you may wish to use Or for one of your criteria.

• YearLevel = 7 Or YearLevel = 8, will select the students from both year levels.

• FileYear = 2007 And FileSemester = 1, will select only students who exist in 2007 and semester 1.

Clicking [Values] will display all values used for this field. Once you have finished adding criteria, click [Close]. To view the criteria that has currently been added to your query, click View >

Criteria (so that there is a tick next to it), these will appear underneath the table(s) that you added.

9. Click File > Return data to Microsoft Excel and save

Query Properties

Several settings that you can save with your query can be found under - Data > Get

External Data > Data Range Properties from Excel.

16

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

17

Parameters

Sometimes you may want to always have a filter on your dataset that can be defined from within Excel when you refresh the data set. This can be done in MS Query by setting the value for a field to be filtered on to a question mark or [] like follows:

or In the above example when the data is next refreshed it will ask for a value to filter on as below:

To put a description in this box or a ‘prompt’ like “Please enter Year Level” 1. a. Add the text between the square brackets as shown below:

Or

b. Select View > Parameters…

18

2. And select [Edit] and enter the description in the Name: field.

It will then be clear to you what the parameter is asking for when you next refresh the data.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

19

Microsoft Word Mail Merge Example 1

Creating Labels with your spreadsheet

Using a Query can save a lot of time when creating labels. All you need to do is import & organise your data, set your stationary type and set up your printer. Using the data you extracted in the first example (using the wizard) called Example1Initials.xls, you can start creating your labels. 1. Make sure you have closed Query and Excel, otherwise you will get sharing

violations 2. Open Word and click Tools > Letters and Mailings > Mail Merge…

and the ‘Mail Merge Wizard’ screen will appear.

Note: if you ever want to reset the settings for a merge, click [Create] > Restore to

Normal Word Document. 3. In Mail Merge wizard, Click Labels then select Next: Starting document to continue

20

4. Select the Label in ‘Label Options…’

5. Click [Select Recipients] > Browse then navigate to the place where you saved

Example1Initials.xls from the first example & click [Open]. Make sure that the file type is set to ‘MS Excel Worksheets (*.xls)’.

6. Select the table and [OK]:

7. The following Mail Merge Recipient list appears:

21

Untick the records you do not want to appear in the merge. 8. Arrange your labels by adding the recipient information in more items option.

9. The next step is to set up the layout of your labels using database fields. This will

place people’s individual details on each label. Click [Insert] for StudentContactMailName then StudentContactAddressFull.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

22

10. Select ‘Preview your labels’

11. Select ‘Update all labels to replicate the arrangement in all labels.

12. Select ‘Preview your labels’

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

23

Microsoft Word Mail Merge Example 2

Creating Letters with your spreadsheet

Start a fresh word document (File > New) This is useful for bulk-mailing purposes. You can place address and name fields that will differ on change of record. 1. Open Word and click Tools > Letters and Mailings >Mail Merge… and the ‘Mail

Merge Wizard’ screen will appear as in previous example. 2. Click ‘Letters’ as a document type and select [Next: Starting document]

3. Click [Next: Select Recipients] and Browse… 4. In the Select Data Source, navigate to the place where you saved

Example1Initials.xls from the first example & click [Open]. Make sure that the file type is set to ‘MS Excel Worksheets (*.xls)’.

5. Select the table and [OK]:

6. The following Mail Merge Recipient list appears:

24

7. Write your letter and add the Merge Field items

8. Now you can insert fields by clicking [Insert Word Merge Field], and selecting from

the list. To view individual details, click the button on Word’s Mail Merge tool-bar.

Example with field names:

25

Example with individual data:

As you can see from the previous examples, Query used in conjunction with Word can provide many opportunities and save a lot of time around the workplace. Try the examples and experiment with various functions within each program yourself. Both Word and Query have fairly extensive on-line help systems which will help you with almost anything. If you have any other questions about queries that are not answered within this manual or the on-line help system, give CDA support a call.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

26

Creating a Mail Merge in MS Word using a MSQuery

You can create a merged letter using fields from Synergetic, by accessing MSQuery via MSWord.

1. Open a blank document or the letter you wish to be merged in Microsoft Word. From the Tools menu, click Letters and Mailings and then Mail Merge

Wizard. 2. Select ‘Letters’ from the options in the window on the right. 3. Follow the prompts – after choosing ‘Select Recipients’ and then ‘Browse’

you will be presented with a screen like the one below:

4. From the tools menu select ‘MSQuery’. 5. MSQuery will now open – you will need to select the correct database ie

SynergyOne or SynergyOneFinance and then you will be prompted to enter your login.

6. Create the query necessary for your merge.

7. Next, from the file menu select ‘Return data to

Word’

8. Now set up your letter with the correct mail merge fields and then select ‘Merge to New Document’.

27

9. To return to MSQuery, select ‘Edit recipient

list’ and then click on the ‘Edit’ button.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

28

Inserting an existing SQL statement Sometimes you may have a query that has already been performed on another system. If the query has not been saved as a .dqy file, then you can use the SQL statement from it. CDA may also e-mail you an SQL statement if you have requested it. This statement is written in a language that the computer can interpret and will perform all the actions that have been described in the two previous examples. A simple SQL statement that will report and total all religion codes in your school:

SELECT vStudents.StudentCampus, vStudents.StudentReligionCode, Count(*)

FROM SynergyOne.dbo.vStudents vStudents

WHERE (vStudents.FileYear=2007) AND (vStudents.FileSemester=1)

GROUP BY vStudents.StudentCampus, vStudents.StudentReligionCode

ORDER BY vStudents.StudentCampus, vStudents.StudentReligionCode

This statement selects student campus, religion code, and places a count field on your spreadsheet. The field filters are placed after the WHERE statement. Groups are placed after the GROUP BY statement, groups will appear together. The sort information is placed after the ORDER BY statement. As you can see, SQL is a fairly easy language to learn. If you know what you are looking at then you can make your queries far more efficient and quicker to run by removing the statements that are not required. For most people, time is of the essence and learning a computer language can be quite difficult to master. In most cases, generation of SQL statements (through query tools & wizard) is much quicker than manually coding your query. Although, knowledge of SQL can open up many data manipulation opportunities. But if you have an existing SQL statement that could be useful for your query, you can insert and run it by doing the following: 1. Load up Query through Excel. Log on to your server but do not go through the

wizard. Close down the ‘Add Tables’ window.

2. Open the SQL window by clicking View > SQL or clicking the button on the top tool-bar.

3. Go to your SQL statement (whether it be in an e-mail, or another text file)

Highlight/block the statement then press [Ctrl]+[c] on your keyboard to copy it Go back to the SQL window in Query then paste the statement by pressing [Ctrl]+[v] on your keyboard.

4. Click [OK] to process your statement.

29

Synergetic also allows you to view SQL Query from a Crystal report. When selecting a crystal report to run, hold down the [Shift] key on the keyboard + click [Preview] button. The [Copy to Clipboard] button will copy to clipboard and allow you to paste into MS Query SQL Statement screen to run as a query.

30

Adding other Tables/Views In some cases, a view may not contain all the fields you need. You will then need to add another table/view to obtain other specific fields. In this example we will use the query created and saved as Example1Initials.xls to obtain student contact information and add award descriptions to inform parents about the award/s their child has received. The award related fields are not available in vStudentContactAddress, so the view vAwards will be added to obtain these fields. 1. Open the Example1Initials.xls and Edit Query (Data > Import External Data > Edit Query… or Right click on cell and select Edit Query…). This will take you back to MS Query. 2. Add a table by selecting the table menu > Add Tables

or clicking . 3. Scroll through the tables list until you find the vAwards view. Double click the view to add it to your query.

4. When you have finished adding tables click [Close] to continue.

Note: If you wish to remove a table, click on a field in it then select Delete on your keyboard. More tables can be added later by clicking Table > Add Tables… from the standard tool-bar.

Linking your tables/views

The views need to be joined in order to link the data. To link your views, join fields that match. The vStudentContactAddress table contains the field ‘ID’. This field returns the ‘StudentID’ field from vAwards.

5. Link your tables – highlight the ‘ID’ field in vStudentContactAddress and drag it to

link with the ‘StudentID’ field in the vAwards table. 6. add the following fields from vAwards to your query:

- AwardClassificationCode - AwardCode - AwardDescription

When vAwards was added to the query, the resulting records give only students with awards. This is due to the type of join between the tables/views.

31

Joins

When you add two or more tables/views to a Query, you will use a join to link the data. Joins are very important in determining the results generated from a MS Query. Unexpected or what seem to be incomplete results is often caused by the use of an incorrect join type for the query.

There are two main types of joins generally used in MS Query – Inner Joins or Outer Joins.

Double clicking on the join allows you to change a join type.

Inner Joins – generally set as default when you join one view/table to another. Results from an inner join includes all the records in which the linked field value in both tables is an exact match.

32

In the example, linking vStudentContactAddress with vAwards using an inner join (default) will return only students who have awards. You will not obtain a record for a student who does not have an award.

Outer Joins

Left Outer Join gives records in the left table (primary table) where the linked field value has no match to the linked view/table.

In the example, changing the link to a Left Outer Join (Join 2) between vStudentContactAddress and vAwards will return records for students who have awards and also students without any awards.

33

The SQL statement gives the following when selecting :

Note that in MS Query, Join 3 is also a Left Outer Join, but has flipped the table/views making the vAwards view the left table (primary table) in this example.

Please note that MS Query only allows an outer join between two tables. It will give the following error:

The SQL statement can be modified manually for advanced query users.

34

Using Finance Tables/Views

Synergetic finance tables and views are found in the SynergyOneFinance database. This will need to be selected if a finance related query is to be created. .

(Users will need to have permission in the SynergyOneFinance database and the finance

tables/views)

The tables listed in MS Query will be finance related.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

35

Using Finance views

Example 1 - Using vEnrolmentDeposits In this example, vEnrolmentDeposits will be used to obtain information about the future/current/past student, the repayee details and information on the enrolment deposit (Deposit code, refundable flag, amount still owing).

1. In MS Query Select Table> vEnrolmentDeposits and [Add]

2. Add the following fields: Repayee1MailNameJoint Repayee2MailNameJoint DepositCode DepositAmountOriginal DepositAmountOwed StudentNameExternal StudentTypeDescription ContactMailNameJoint DefinitionRefundableFlag DefinitionStudentBasedFlag

3. Sort by DepositCode 4. Return the data to Excel and format the amount columns to currency with two

decimal places. 5. Save as EnrolDepInitials.xls

36

Example 2 - Using vCashReceiptsEntry Another commonly used finance view is vCashReceiptsEntry. This is often used to analyse receipts processed in a particular posting or date/date range. 1. In MS Query, create a new query and add vCashReceiptsEntry 2. Add the following fields:

4. Add a criteria for the PostingDate field – use the In Between operator.

Type the date range in the value field as below (see pg 38 re Date formats in ms query):

5. This will appear in the Criteria section as shown:

6. Return the data to Excel and format the amount columns to currency with two

decimal places.

7. Save as CashReceiptsInitials.xls

37

MSQuery / benefits / disadvantages

Benefits

- Quick - Easy - Already licensed on all computers with Microsoft Office installed - Gives you the ability to create custom lists - Gives you the ability to do custom mail merges / labels

Disadvantages

- MSQuery is not installed by default when Word is installed (refer your IT Dept) - If you create a query with the wizard, when you change it later, you are put back

into the wizard - You may get results that look good, feel good but actually stink!

Queries

List of Parents Names and Year Level (vStudentContactAddress) All Students who are in a Class (vStudentClasses) All Students in multiple year levels (vStudents) Parent Constituencies versus Contacts. (vCommunityAddressConstit) All parents who are builders (vStudentContactsParentsDebtor) All Students who are also Future Students (constituencies or vFutureStudents JOIN vStudents) All Student Contacts for students in tag list (vStudentContactAddress Join vTagsOwn) One record per family (Distinct) (Family Position) All Parents who are past students (vPastStudents JOIN Constituencies) All Mothers or All Parents (vStudentContactsParentsDebtor) Magazine Mailing – One magazine per Address as ‘The Lynch Family’ (crspCommunityCommsCurrent)

38

Dates:-

In Add Criteria Wizard Either 2000-01-30 OR 31/1/2000 (assuming your computer is set for Australia) In Criteria Field Either #2000-07-20# or #31/05/2000# In SQL Statements WHERE (Community.BirthDate>{ts '2000-01-30 00:00:00'})

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

39

MS Query Exercises In the following exercises, determine the best view/tables to use to create the query. 1. Create a query to obtain a list of students who have a public medical alert and include the public medical alert comment. 2. Create a query giving Student Contact Given names, surname, default emails, mobile number and home number based on students in a tag list. 3. Find Past Students living in NSW for a reunion 4. Generate a list of donors (including amount donated) who have donated to the Building Fund ‘B’. Add a criterion to give only donations of over $1000. 5. Generate a list of debtors who have made payments in the current month. 6. Generate a list of debtors who have been sent overdue letters this year. Also include the students linked to the debtor and the student/s year level and house. 7. Generate a list of creditors with any outstanding invoices.

NOTES:

_________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________ _________________________________________________________________________

40

Advanced Microsoft Query & SQL Examples

Microsoft Query is a tool that is used to create SQL statements that will extract and graphically display virtually any data that you want from the Synergetic database. Crystal Reports allows you to produce similar results but allows a lot more manipulation of the data from a graphical perspective. See Crystal Reports in the School & Community manual or contact Computing Directions Australia for more information. Following is some intermediate to advanced SQL statements that you can use with Microsoft Query.

Standard Checks and Validations – SynergyOne Data

DeceasedFlag = 0 ValidAddressFlag = 1

FileSemester = 1 FileYear = 2000 StudentStatus eg. 4 = Left / 1 = Normal StudentContactType SC1 (Contact 1) or SC2 (Contact 2) LivesWithFlag Student lives with this contact

Example A. Use SUBSTRING with a character string

This example shows how to return only a portion of a character string. From the Student Classes View, this query returns the portion of the Class Code selected out from within the whole Class Code.

SELECT vSC.StudentID, vSC.StudentSurname, vSC.StudentPreferred, vSC.StudentCampus, vSC.StudentHouse, vSC.ClassCampus, vSC.ClassCode, vSC.ClassDescription

FROM vStudentClasses vSC

WHERE (substring(vSC.ClassCode,2,3)='MAT')

ORDER BY vSC.StudentSurname, vSC.StudentPreferred

The WHERE substring statement selects MAT because there is a character match starting in position 2 and includes position 3 and 4 of the Class Code.

• Here is how to display the third and fourth characters of the string constant abcdef. SELECT x = SUBSTRING('abcdef', 3, 2)

Here is the result set: cd

Example B. Mail Names & Addresses for Current Parents & Staff SELECT MailNameJoint, AddressFull

FROM Community LEFT JOIN Addresses ON Community.AddressID = Addresses.AddressID

41

WHERE EXISTS (SELECT * from Constituencies WHERE Community.ID = Constituencies.ID AND ConstitCode = '@PC')

AND EXISTS (SELECT * from Constituencies WHERE Community.ID = Constituencies.ID AND ConstitCode = '@STF')

AND DeceasedFlag = 0

AND ValidAddressFlag = 1

Points to note: • [NOT] EXISTS Specifies the search for an expression, based on the expression’s

inclusion in or exclusion from a list. The search expression can be a constant or a column name, and the list can be a set of constants or, more commonly, a subquery. Enclose the list of values in parentheses.

Example C. All Parents who are also staff members (Primary or Spouse) SELECT DISTINCT StudentContactMailName, StudentContactAddressFull from vStudentContactAddress

LEFT JOIN Community on StudentContactID = Community.ID

WHERE EXISTS (SELECT * from Constituencies

WHERE vStudentContactAddress.StudentContactID = Constituencies.ID AND ConstitCode = '@STF') OR EXISTS (

SELECT * from Constituencies WHERE SpouseID = Constituencies.ID AND ConstitCode = '@STF')

Points to note:

• DISTINCT Specifies that only unique rows can appear in the returned data set. Null values are considered equal for the purposes of this keyword.

• LEFT JOIN Specifies that all rows from the left table that are not meeting the join condition are included in the results set, and output columns from the other table are set to NULL in addition to all rows returned by the inner join.

• INNER JOIN Specifies all matching

Example D. Selecting Records in MSQuery on the basis of Date Fields:

MSQUERY SELECT ENQUIRIES IN LAST 7 DAYS SELECT vEnquiryContactAddress.EnquiryID,

vEnquiryContactAddress.EnquiryDate

FROM vEnquiryContactAddress

WHERE

{fn TIMESTAMPDIFF(SQL_TSI_DAY, {fn CURDATE()}, vEnquiryContactAddress.EnquiryDate)} > -6

The –6 means select all enquiries for today plus the last 7 days. Change the –6 to 0 for TODAY only. You can change to any other value to select enquiries from that many days ago. You MUST enter the number of days with the minus sign (means PRIOR to today).

Example E. Selecting students who have siblings at the school:

What factor determines siblings?

- Primary Contact

42

The Primary Contact is the person or Primary person of a couple who, as far as the school is concerned, is the main responsible person for the child.

The child does not necessarily need to live at the address - but its normally the case.

The accounts do not need to be sent to the Primary Contact - that's the meaning of the Debtor on the Debtor tab, but again, its normally the case.

One meaning which is attached to the Primary Contact is that its the means by which the system tries to work out who are siblings. ie, two students who share the same primary contact are assumed to be siblings. It does not differentiate between normal and step-siblings - that's the purpose of relationships. Its used for the following purposes:- - Determining Family Position: StudentFamilyPosition of 1 is always the eldest

by birth date - Determining Sibling discounts: for billing debtor accounts - The sibling tab in Current and Future Students.

The following query may be able to be used in Microsoft Query to find all FutureStudents who have a sibling (by the definition above) who is currently enrolled.

SELECT * FROM vFutureContactAddress

WHERE FutureContactID IN

(SELECT StudentContactID from vStudentContactAddress

WHERE StudentContactType = 'SC1'

AND CurrentSemesterOnlyFlag = 1

AND vStudentContactAddress.ID <> vFutureContactAddress.ID)

AND FutureContactType = 'SC1'

Example F. Selecting the oldest student in a family from a subgroup in the school:

In the query below, the eldest child from each family in the Junior School campus is returned. The query first selects all current students and their primary contacts from the current semester. A subquery is then used to find the lowest student family position that exists within a specified subgroup. The subquery is linked on the students contacts, and the file year and file semester to ensure that the family position from each student in a family is evaluated. SELECT ID, Surname, Preferred, StudentContactMailname

FROM vStudentContactAddress A

WHERE CurrentSemesterOnlyFlag = 1 AND

StudentContactType = 'SC1' AND

StudentFamilyPosition > 0 AND

43

ISNULL(StudentLeavingDate, '31 DEC 9999') > GetDate() AND

StudentFamilyPosition IN

(SELECT MIN(SS.FamilyPosition)

FROM StudentContacts SC

JOIN StudentSemester SS ON SC.ID = SS.ID

JOIN Students S ON SC.ID = S.ID

WHERE SC.LinkedID = A.StudentContactID AND

SC.ContactType = 'SC1' AND

SS.FileYear = A.FileYear AND

SS.FileSemester = A.FileSemester AND

ISNULL(S.LeavingDate, '31 DEC 9999') > Getdate() AND

SS.StudentCampus = 'J')

Note: GetDate() is used to pass the current date into the query.

MSQUERY SELECT ENROLMENT CHANGES IN LAST 7 DAYS

You can also use the following statement to select records changed during the previous day(s). This statement will only work in the current year – ie you can not select records changed previous to the current year.. The query uses the SQL DATEPART function to calculate the date range required.

SELECT vFCA.FutureSurname, vFCA.FuturePreferred, vFCA.FutureGender, vFCA.FutureContactType, vFCA.FutureContactDescription, vFCA.FutureContactMailName, vFCA.FutureContactMailSalutation, vFCA.FutureContactAddressFull, vFCA.FutureApplicationDate, vFCA.FutureEnrolYear, vFCA.FutureStatus, vFCA.FutureCampus, vFCA.FutureYearLevel

FROM SynergyOne.dbo.vFutureContactAddress vFCA

WHERE

(DATEPART(Year,FutureStatusChangeDate) = DATEPART(Year,GETDATE())) AND (DATEPART(DayofYear,FutureStatusChangeDate) >= DATEPART(DayofYear,GETDATE()-6))

SUBSTRING FUNCTION

Returns part of a character, binary, text, or image expression. For more information about the valid Microsoft® SQL Server™ data types that can be used with this function, see Data Types. Syntax SUBSTRING(expression, start, length) Arguments

• expression is a character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.

• start is an integer that specifies where the substring begins.

• length is an integer that specifies the length of the substring (the number of characters or bytes to return).

44

Note Because start and length specify the number of bytes when SUBSTRING is used on text data, DBCS data, such as Kanji, may result in split characters at the beginning or end of the result. This behaviour is consistent with the way in which READTEXT handles DBCS; however, because of the occasional strange result, it is advisable to use ntext instead of text for DBCS characters. Return Types Returns character data if expression is one of the supported character data types. Returns binary data if expression is one of the supported binary data types. The returned string is the same type as the given expression with the exceptions shown in the table. Given expression Return type text varchar image varbinary ntext nvarchar Remarks

Offsets (start and length) using the ntext, char, or varchar data types must be specified in number of characters. Offsets using the text, image, binary, or varbinary data types must be specified in number of bytes.

Note: Compatibility levels can affect return values.

Related/Further Information For further detailed information there are many decent SQL websites that assist in learning this database language but you can also get more info from Enterprise Manager. If you have access to SQL Enterprise Manager (your Network Admin most likely would), you can load “SQL Books On-line” or the “Transact-SQL Help” through SQL

Query Analyser.