Working out frequency in sql? - sql

I am creating a database for a library with the following four tables.
Table 1 - book
isbn title author
111-2-33-444444-5 Pro JavaFX Dave Smith
222-3-44-555555-6 Oracle Systems Kate Roberts
333-4-55-666666-7 Expert jQuery Mike Smith
Table 2 - copy
code isbn duration
1011 111-2-33-444444-5 21
1012 111-2-33-444444-5 14
1013 111-2-33-444444-5 7
2011 222-3-44-555555-6 21
3011 333-4-55-666666-7 7
3012 333-4-55-666666-7 14
Table 3 - student
no name school embargo
2001 Mike CMP No
2002 Andy CMP Yes
2003 Sarah ENG No
2004 Karen ENG Yes
2005 Lucy BUE No
Table 4 - loan
code no taken due return
1011 2002 2015.01.10 2015.01.31 2015.01.31
1011 2002 2015.02.05 2015.02.26 2015.02.23
1011 2003 2015.05.10 2015.05.31
1013 2003 2014.03.02 2014.03.16 2014.03.10
1013 2002 2014.08.02 2014.08.16 2014.08.16
2011 2004 2013.02.01 2013.02.22 2013.02.20
3011 2002 2015.07.03 2015.07.10
3011 2005 2014.10.10 2014.10.17 2014.10.20
I have been looking into working out the frequency of book loans throughout this database. I am looking for create a query that will show me the frequency of all books that have been loaned 2 or more times.
I understand that I would have to take 'code' from loan and find rows with the same code, but I am completely lost on how to work out the frequency. Could anyone help me out here?

Related

Loop through a table based on multiple conditions

Students table
student_id student_name
1 John
2 Mary
Grades table
student_id year grade_level school Course Mark
1 2015 10 Smith High Algebra 95
1 2015 10 Smith High English 96
1 2016 11 Smith High Geometry 85
1 2016 11 Smith High Science 88
2 2015 10 Smith High Algebra 98
2 2015 10 Smith High English 93
2 2016 11 Smith High Geometry 97
2 2016 11 Smith High Science 86
I'm trying to show results for each year and what class a student took with the grade.
So the final output i'm looking for is something like:
[student_id1] [year1] [grade1] [school1]
[course1] [mark1]
[course2] [mark2]
[course3] [mark3]...
[student_id1] [year2] [grade2] [school1]
[course1] [mark1]
[course2] [mark2]
[course3] [mark3]...
[student_id2] [year1] [grade1] [school1]
[course1] [mark1]
[course2] [mark2]
[course3] [mark3]...
This would all go in one column/row. So in this particular example, this would be my result:
1 2015 10 Smith High
Algebra 95
English 96
1 2016 11 Smith High
Geometry 85
Science 88
2 2015 10 Smith High
Algebra 98
English 93
2 2016 11 Smith High
Geometry 97
Science 86
So anytime a student id, year, grade, or school name changes, I would have a line for that and loop through the classes taken within that group. And all of this would be in one column/row.
This is what I have so far but I'm not sure how I can properly loop through course and grades for each group. I'd appreciate it if I can be pointed in the right direction.
select s.student_id + '' + year + '' + grade_level + '' + school
from students
join grades on students.student_id = grades.student_id
If you want to do it in your SQL Enviromnment, it depends on the Database Management System you are using.
For example, if you are using Transact SQL you can try to look at this link.
Generally this kind of loops and interactions are done in the programming language that is coupled with the SQL DB.
Anyway, you should look at Stored Procedures and Cursors if you really want to do this in SQL.
You are trying to mix presentation with retrieval of data from database tables. Looping through the resultset in sql can be achieved via cursor but that isn't adviced. You are better off by pulling the required data using two queries and later print it using a language of your choice.

SQL Query sorted by date

looking for query help on this. what would be the query for the below results.
List of all apartments that were occupied on March 1, 2015 sorted by complex and apartment number.
ComplexName ApartmentNumber
-----------------------------
Fox Run 101
Fox Run 102
Fox Run 204
Oak Meadows 103
Villa Maria 11
Villa Maria 12
List of all tenants that had a current lease on March 1, 2015 sorted by property and apartment number
Example results:
ComplexName ApartmentNumber GivenName FamilyName
----------------------------------------------------------
Fox Run 101 Shannon McCoy
Fox Run 102 Larry Thomas
Fox Run 204 Mark Patterson
Oak Meadows 103 Jose Ortiz
Villa Maria 11 Cassie Lee
Villa Maria 12 Robert Woodward
Sum of all rent paid in 2015 grouped by property and month
Example results:
ComplexName Month Rent Revenue
--------------------------------------
Fox Run March 1250.00
Oak Meadows March 1500.00
Oak Meadows April 700.00
Villa Maria March 1200.00
Villa Maria April 600.00
What are you table names and column names, it is difficult to give advice without these: For example if your table was called apartments and had a column occupieddate and appartment number
SELECT *
FROM Apartments
WHERE
occupieddate ='03/01/2015'
ORDER BY
Appartment number;
Could be an answer to your first question

SQL logic for getting records in a single row for a unique id

![Cognost reports studio Query Explorer]
Below is the snapshot of a table.
**Acctno ClientNo ClientName PrimaryOffId SecondaryOffID**
101 11111 ABC corp 3 Not Defined
102 11116 XYZ Inc 5 Not Defined
103 11113 PQRS Corp 2 9
104 55555 Food LLC 4 11
105 99999 Kwlg Co 1 Not Defined
106 99999 Kwlg Co 1 Not Defined
107 11112 LMN Corp Not Defined 6
108 11112 LMN Corp Not Defined 6
109 11115 Sleep Co 4 10
110 44444 Cool Co Not Defined 8
111 11114 Sail LLC 3 Not Defined
112 66666 Fun Inc 1 Not Defined
113 88888 Job LLC 5 12
114 22222 Acc Co Not Defined Not Defined
115 77777 Good Corp 2 Not Defined
116 33333 City LLC Not Defined 7
117 33333 City LLC Not Defined 7
118 33333 City LLC Not Defined 7
119 11111 ABC corp 3 Not Defined
I want to replace PrimaryOffID and SecondaryOffID with their Names coming from this table
EmpID Names
1 Cathy
2 Chris
3 John
4 Kevin
5 Mark
6 Celine
7 Jane
8 Phil
9 Jess
10 Jose
11 Nick
12 Rosy
The Result should look like this: Notice that, If Cathy is the PrimaryOfficer, she can't be the Secondary Officer and vice versa. This logic is applicable for all the Names
Acctno ClientNo Client Name PrimOffName SecondaryOffName
101 11111 ABC corp John Not Defined
102 11116 XYZ Inc Mark Not Defined
103 11113 PQRS Corp Chris Jess
104 55555 Food LLC Kevin Nick
105 99999 Kwlg Co Cathy Not Defined
106 99999 Kwlg Co Cathy Not Defined
107 11112 LMN Corp Not Defined Celine
108 11112 LMN Corp Not Defined Celine
109 11115 Sleep Co Kevin Jose
110 44444 Cool Co Not Defined Phil
111 11114 Sail LLC John Not Defined
112 66666 Fun Inc Cathy Not Defined
113 88888 Job LLC Mark Rosy
114 22222 Acc Co Not Defined Not Defined
115 77777 Good Corp Chris Not Defined
116 33333 City LLC Not Defined Jane
117 33333 City LLC Not Defined Jane
118 33333 City LLC Not Defined Jane
119 11111 ABC corp John Not Defined
But Instead it looks like this:
Acctno ClientNo ClientName PrimOffName SecondaryOffName
101 11111 ABC corp John Not Defined
102 11116 XYZ Inc Mark Not Defined
103 11113 PQRS Corp Chris Not Defined
103 11113 PQRS Corp Not Defined Jess
104 55555 Food LLC Kevin Not Defined
104 55555 Food LLC Not Defined Nick
105 99999 Kwlg Co Cathy Not Defined
106 99999 Kwlg Co Cathy Not Defined
107 11112 LMN Corp Not Defined Celine
108 11112 LMN Corp Not Defined Celine
109 11115 Sleep Co Kevin Not Defined
109 11115 Sleep Co Not Defined Jose
110 44444 Cool Co Not Defined Phil
111 11114 Sail LLC John Not Defined
112 66666 Fun Inc Cathy Not Defined
113 88888 Job LLC Mark Not Defined
113 88888 Job LLC Not Defined Rosy
114 22222 Acc Co Not Defined Not Defined
115 77777 Good Corp Chris Not Defined
116 33333 City LLC Not Defined jane
117 33333 City LLC Not Defined jane
118 33333 City LLC Not Defined jane
119 11111 ABC corp John Not Defined
Notice that, now the Acctno is no more unique, Where ever the Names should have been in both the fields together, it separates and gives the output in the next row creating multiple records. i tried various options but it didn't work. Please be aware, that I am creating this report in Cognos Studio. Please suggest the possible query to get the desired result. Thanks in Advance. Appreciate your help.
You don't state which version of Cognos you're using. "Cognos Studio" is ambiguous. I'm most familiar with 8.4.1, but even then you don't say if you're trying to define this in the Cognos model, Query Studio, Event Studio or Report Studio.
Second, you should always show what you've got so far when asking questions on StackOverflow. People want to see what you have done to show you want to fix, not repeat the lion's share of the work. That's why you got downvotes.
As far as plain SQL, you'll want to do this:
SELECT a.Acctno, a.ClientNo, a.ClientName, coalesce(e1.Names,'Not Defined') "PrimaryOffName", coalesce(e2.Names,'Not Defined') "SecondaryOffName"
FROM Account a
LEFT OUTER JOIN Emp e1
ON t.PrimaryOffID = e1.EmpID
LEFT OUTER JOIN Emp e2
ON t.PrimaryOffID = e2.EmpID
I made up table names. You can do this in Report Studio by creating two queries for Emp and outer joining them in succession to the Account query.
If you're able to, you'll want to move the OffID fields to a separate juntion table and remove them from the Account table. You can then create a Status field or flag in that junction table that identifies primary and secondary.

VBA/SQL recordsets

The project I'm asking about is for sending an email to teachers asking what books they're using for the classes they're teaching next semester, so that the books can be ordered. I have a query that compares the course number of this upcoming semester's classes to the course numbers of historical textbook orders, pulling out only those classes that are being taught this semester. That's where I get lost.
I have a table that contains the following:
Professor
Course Number
Year
Book Title
The data looks like this:
professor year course number title
--------- ---- ------------- -------------------
smith 13 1111 Pride and Prejudice
smith 13 1111 The Fountainhead
smith 13 1222 The Alchemist
smith 12 1111 Pride and Prejudice
smith 11 1222 Infinite Jest
smith 10 1333 The Bible
smith 13 1333 The Bible
smith 12 1222 The Alchemist
smith 10 1111 Moby Dick
johnson 12 1222 The Tipping Point
johnson 11 1333 Anna Kerenina
johnson 10 1333 Everything is Illuminated
johnson 12 1222 The Savage Detectives
johnson 11 1333 In Search of Lost Time
johnson 10 1333 Great Expectations
johnson 9 1222 Proust on the Shore
Here's what I need the code to do "on paper":
Group the records by professor. Determine every unique course number in that group, and group records by course number. For each unique course number, determine the highest year associated. Then spit out every record with that professor+course number+year combination.
With the sample data, the results would be:
professor year course number title
--------- ---- ------------- -------------------
smith 13 1111 Pride and Prejudice
smith 13 1111 The Fountainhead
smith 13 1222 The Alchemist
smith 13 1333 The Bible
johnson 12 1222 The Tipping Point
johnson 11 1333 Anna Kerenina
johnson 12 1222 The Savage Detectives
johnson 11 1333 In Search of Lost Time
I'm thinking I should make a record set for each teacher, and within that, another record set for each course number. Within the course number record set, I need the system to determine what the highest year number is - maybe store that in a variable? Then pull out every associated record so that if the teacher ordered 3 books the last time they taught that class (whether it was in 2013 or 2012 and so on) all three books display. I'm not sure I'm thinking of record sets in the right way, though.
My SQL so far is basic and clearly doesn't work:
SELECT [All].Professor, [All].Course, Max([All].Year)
FROM [All]
GROUP BY [All].Professor, [All].Course;
Use your query as a subquery and INNER JOIN it back to the [ALL] table to filter the rows.
SELECT
a.Professor,
a.Year,
a.Course,
a.title
FROM
[ALL] AS a
INNER JOIN
(
SELECT [All].Professor, [All].Course, Max([All].Year) AS MaxOfYear
FROM [All]
GROUP BY [All].Professor, [All].Course
) AS sub
ON
a.Professor = sub.Professor
AND a.Course = sub.Course
AND a.Year = sub.MaxOfYear;

Query to run through each instance. MS-Access

I have a MS-Access database with two tables which I would like to query from, the basic table schema is shown below. I am looking to pull out the details for the earliest parish church in each parish – and in the instance that there is no church with ‘parish’ in the name; I would like to pull out the earliest church.
SITEDETAIL:
Site
Reference No. | Civil Parish | Site Name | NGR East | NGR North
1 Assynt Old Parish Church 6137 3172
2 Assynt St. Marys 6097 3870
3 Assynt New Parish Church 6249 3490
4 Bower Grimbister 2095 4067
5 Bower St. Andrews 2304 3194
6 Halkirk Firth Parish Church 7136 3450
7 Holm Strath Parish Church 4586 2045
8 Holm St Nicholas Parish 4132 3146
SITEDATES:
Site
Reference No. | Date
1 1812
2 1300
3 1900
4 1760
5 1750
6 1838
7 1619
8 1774
I have written a query that pulls out all the instances of ‘parish’:
SELECT SITEDETAIL.SITEREFNO, SITEDETAIL.CIVPARBUR_CDE, SITEDETAIL.SITENAME, SITEDETAIL.NGRE, SITEDETAIL.NGRN, SITEDATES.DATE
FROM SITEDETAIL INNER JOIN SITEDATES ON SITEDETAIL.SITEREFNO = SITEDATES.SITEREFNO
WHERE (((SITEDETAIL.SITENAME) Like "par*"));
However, this does not take into account the instances of multiple/no churches with ‘par*’ in the name.
Is it possible to create an SQL query that runs through each civil parish and selects the earliest ‘parish’ or earliest church, or is it necessary to write a perl script to run through them? Is this possible using DBI?
Desired output:
Site
Reference No. | Civil Parish | Site Name | NGR East | NGR North | Date
1 Assynt Old Parish Church 6137 3172 1812
5 Bower St. Andrews 2304 3194 1750
6 Halkirk Firth Parish Church 7136 3450 1838
7 Holm Strath Parish Church 4586 2045 1619
NB:In the case of Assynt, 'Old Parish Church' is selected despite being older because of having 'parish' in the name.
The following query should get you what you need. It's a little long, but it does the trick:
`select LIST.Civil_Parish, SD.Site_name, LIST.MSite_Date
from
(
select Civil_Parish, min(Site_date) as MSite_date
from SiteDetail
where Boolean = 1
group by Civil_Parish
union
select Civil_parish, min(Site_date) as MSite_date
from SiteDetail
where Civil_parish not in
(select Civil_parish
from SiteDetail
where Boolean = 1)
group by Civil_Parish) as LIST
left join sitedetail SD on LIST.Civil_Parish = SD.Civil_Parish and LIST.MSite_Date = SD.Site_Date`
Please note the following:
1) I am using PowerUser's boolean suggestion. If the Boolean column has value 1, then the row is a Parish Church, and 0 if it is not.
2) I combined the tables "SiteDates" and "SiteDetails" for the purpose of this example, as they are 1 to 1.
The core of the query is A) finding the oldest Parish church in a Parish, then B) find Parishes without Parish Churches.
The code for A) is as follows:
'select Civil_Parish, min(Site_date) as MSite_date
from SiteDetail
where Boolean = 1
group by Civil_Parish'
We then union that with the oldest churches in parishes that do not have a parish church:
'select Civil_parish, min(Site_date) as MSite_date
from SiteDetail
where Civil_parish not in
(select Civil_parish
from SiteDetail
where Boolean = 1)
group by Civil_Parish'
We then join the union query (named "LIST" here) with our original "SITEDETAIL" table on Parish and Date to bring in the church name.