How can I join tables using information from different rows? - sql

I have two similar tables that I would like to join. See reproducible example below.
WHAT NEEDS TO BE DONE
See comments in code: concatenating the values '2021-01-01'(column: Date), 'hat'(column: content), 'cat'(column: content) and 'A'(column: Tote) in first_table would lead to a unique key that can be joined with the exact same data in second_table. The result would be the first row of the 4 unique events (see desired_result: '#first tote'). In reality the rows would be a few million.
Reproducible example:
CREATE OR REPLACE TABLE
`first_table` (
`Date` string NOT NULL,
`TotearrivalTimestamp` string NOT NULL,
`Tote` string NOT NULL,
`content` string NOT NULL,
`location` string NOT NULL,
);
INSERT INTO `first_table` (`Date`, `TotearrivalTimestamp`, `Tote`, `content`, `location`) VALUES
('2021-01-01', '13:00','A','hat','1'), #first tote
('2021-01-01', '13:00','A','cat','1'), #first tote
('2021-01-01', '14:00', 'B', 'toy', '1'),
('2021-01-01', '14:00', 'B', 'cat', '1'),
('2021-01-01', '15:00', 'A', 'toy', '1'),
('2021-01-01', '13:00', 'A', 'toy', '1'),
('2021-01-02', '13:00', 'A', 'hat', '1'),
('2021-01-02', '13:00', 'A', 'cat', '1');
CREATE OR REPLACE TABLE
`second_table` (
`Date` string NOT NULL,
`ToteendingTimestamp` string NOT NULL,
`Tote` string NOT NULL,
`content` string NOT NULL,
`location` string NOT NULL,
);
INSERT INTO `second_table` (`Date`, `ToteendingTimestamp`, `Tote`, `content`, `location`) VALUES
('2021-01-01', '20:00', 'B', 'cat', '2'),
('2021-01-01', '19:00', 'A', 'cat', '1'), #first tote
('2021-01-01', '19:00', 'A', 'hat', '1'), #first tote
('2021-01-01', '20:00', 'B', 'toy', '2'),
('2021-01-01', '14:00', 'A', 'toy', '1'),
('2021-01-02', '14:00', 'A', 'hat', '1'),
('2021-01-02', '14:00', 'A', 'cat', '1'),
('2021-01-01', '16:00', 'A', 'toy', '1');
CREATE OR REPLACE TABLE
`desired_result` (
`Date` string NOT NULL,
`Tote` string NOT NULL,
`TotearrivalTimestamp` string NOT NULL,
`ToteendingTimestamp` string NOT NULL,
`location_first_table` string NOT NULL,
`location_second_table` string NOT NULL,
);
INSERT INTO `desired_result` (`Date`, `Tote`, `TotearrivalTimestamp`, `ToteendingTimestamp`, `location_first_table`, `location_second_table`) VALUES
('2021-01-01', 'A', '13:00', '19:00', '1', '1'), #first tote
('2021-01-01', 'B', '14:00', '20:00', '1', '1'),
('2021-01-01', 'A', '15:00', '16:00', '1', '2'),
('2021-01-02', 'A', '13:00', '14:00', '1', '1');
#### this does not give what I want####
select first.date as Date, first.tote, first.totearrivaltimestamp, second.toteendingtimestamp, first.location as location_first_table, second.location as location_second_table
from `first_table` first
inner join `second_table` second
on first.tote = second.tote
and first.content = second.content;

I was able to reproduce the'desired_result' table (mostly) with the SQL below. I believe there exists a few typos with the 'insert into' statements. However, I think this meets the intent.
Query:
select
first_table.date as Date,
first_table.tote,
first_table.totearrivaltimestamp,
second_table.toteendingtimestamp,
first_table.location as location_first_table,
second_table.location as location_second_table
from first_table
inner join `second_table`
on first_table.Date = second_table.Date
and first_table.tote = second_table.tote
group by first_table.Date, first_table.TotearrivalTimestamp, first_table.tote;
result:
2021-01-01|A|13:00|19:00|1|1
2021-01-01|B|14:00|20:00|1|2
2021-01-01|A|15:00|19:00|1|1
2021-01-02|A|13:00|14:00|1|1
This result assumes your first table dates will always match for totes/timestamps. The group by function then merges duplicate results. The second table information matches the date and tote of the first table and is appended to the line item.

This answer should work. I think your issue might be with some of your quoting of tables....
select f.'date'
,f.tote
, f.totearrivaltimestamp
, s.toteendingtimestamp
, f.location as location_first_table
, s.location as location_second_table
from first f
,INNER JOIN "second" s on f.'date' = s.'date'
and f.tote = s.tote
and f.content = s.content

Related

create one concatenated value out of multiple rows

See reproducible example below.
WHAT NEEDS TO BE DONE
See comments in code: creating unique totes using '2021-01-01'(column: Date) and 'A'(column: Tote, while creating a concatenated string from 'hat'(column: content) and 'cat'(column: content) in alphabetic order.
Reproducible example:
CREATE OR REPLACE TABLE
`first_table` (
`Date` string NOT NULL,
`TotearrivalTimestamp` string NOT NULL,
`Tote` string NOT NULL,
`content` string NOT NULL,
`location` string NOT NULL,
);
INSERT INTO `first_table` (`Date`, `TotearrivalTimestamp`, `Tote`, `content`, `location`) VALUES
('2021-01-01', '13:00','A','hat','1'), #first tote
('2021-01-01', '13:00','A','cat','1'), #first tote
('2021-01-01', '14:00', 'B', 'toy', '1'),
('2021-01-01', '14:00', 'B', 'cat', '1'),
('2021-01-01', '15:00', 'A', 'toy', '1'),
('2021-01-01', '13:00', 'A', 'toy', '1'),
('2021-01-02', '13:00', 'A', 'hat', '1'),
('2021-01-02', '13:00', 'A', 'cat', '1');
CREATE OR REPLACE TABLE
`desired_result` (
`Date` string NOT NULL,
`Tote` string NOT NULL,
`TotearrivalTimestamp` string NOT NULL,
`content_combination` string NOT NULL,
);
INSERT INTO `desired_result` (`Date`, `Tote`, `TotearrivalTimestamp`, `content_combination`) VALUES
('2021-01-01', 'A', '13:00', 'cathat'), #first tote
('2021-01-01', 'B', '14:00', 'cattoy'),
('2021-01-01', 'A', '15:00', 'toy'),
('2021-01-02', 'A', '13:00', 'cathattoy');
From the backticks I conclude this is MySQL. In MySQL the string aggregation function is called GROUP_CONCAT:
select
date, tote,totearrivaltimestamp,
group_concat(content order by content separator '') as content_combination
from mytable
group by date, tote,totearrivaltimestamp
order by date, tote,totearrivaltimestamp;
STRING_AGG() did the trick - worked for me

Selecting from Stored Procedures and Storing SP Results into a Table

I'm trying to build a couple of tables based upon the results of a few Stored procedures inside an Informix Database, that I cannot edit, and the parameter of the second SP requires values from another (will be called a few times). I have figured out what to do, but am having trouble executing it, predominantly because I cannot save my DB into a Temp table so I can then modify it.
If someone could give me some pointers, that would be great.
Some examples of things I've tried
call <stored procedure(...)> INTO TEMP db
and
create temp table name(...)
INSERT INTO namefrom storedprocedure()
and
create temp table name(...)
Select INTO name from storedprocedure()
Kind Regards,
Fox
Here's an example of a user-defined function (aka stored procedure) returning multiple values that are inserted into a temporary table. It uses the stores_demo database.
create function func1()
returning char(15), char(15);
define v_fname, v_lname char(15);
foreach select fname, lname into v_fname, v_lname from customer
return v_fname, v_lname with resume;
end foreach
end function;
create temp table tt1(fname char(15), lname char(15));
insert into tt1 execute function func1();
You can use:
SELECT * FROM TABLE(stored_procedure()) INTO TEMP p32;
This inserts the rows returned by the stored procedure into the temporary table p32.
There may be other ways to do it, but this seemed to work and is fairly straight-forward to understand.
(Tested: Informix 12.10.FC6 on a Mac running macOS 10.14.6 Mojave.)
Test schema
CREATE TABLE elements
(
atomic_number INTEGER NOT NULL PRIMARY KEY
CHECK (atomic_number > 0 AND atomic_number < 120),
symbol CHAR(3) NOT NULL UNIQUE,
name CHAR(20) NOT NULL UNIQUE,
atomic_weight DECIMAL(8, 4) NOT NULL,
pt_period SMALLINT NOT NULL
CHECK (pt_period BETWEEN 1 AND 7),
pt_group CHAR(2) NOT NULL
-- 'L' for Lanthanoids, 'A' for Actinoids
CHECK (pt_group IN ('1', '2', 'L', 'A', '3', '4', '5', '6',
'7', '8', '9', '10', '11', '12', '13',
'14', '15', '16', '17', '18')),
stable CHAR(1) DEFAULT 'Y' NOT NULL
CHECK (stable IN ('Y', 'N'))
);
INSERT INTO elements VALUES( 1, 'H', 'Hydrogen', 1.0079, 1, '1', 'Y');
INSERT INTO elements VALUES( 2, 'He', 'Helium', 4.0026, 1, '18', 'Y');
INSERT INTO elements VALUES( 3, 'Li', 'Lithium', 6.9410, 2, '1', 'Y');
INSERT INTO elements VALUES( 4, 'Be', 'Beryllium', 9.0122, 2, '2', 'Y');
INSERT INTO elements VALUES( 5, 'B', 'Boron', 10.8110, 2, '13', 'Y');
INSERT INTO elements VALUES( 6, 'C', 'Carbon', 12.0110, 2, '14', 'Y');
INSERT INTO elements VALUES( 7, 'N', 'Nitrogen', 14.0070, 2, '15', 'Y');
INSERT INTO elements VALUES( 8, 'O', 'Oxygen', 15.9990, 2, '16', 'Y');
INSERT INTO elements VALUES( 9, 'F', 'Fluorine', 18.9980, 2, '17', 'Y');
INSERT INTO elements VALUES( 10, 'Ne', 'Neon', 20.1800, 2, '18', 'Y');
INSERT INTO elements VALUES( 11, 'Na', 'Sodium', 22.9900, 3, '1', 'Y');
INSERT INTO elements VALUES( 12, 'Mg', 'Magnesium', 24.3050, 3, '2', 'Y');
INSERT INTO elements VALUES( 13, 'Al', 'Aluminium', 26.9820, 3, '13', 'Y');
INSERT INTO elements VALUES( 14, 'Si', 'Silicon', 28.0860, 3, '14', 'Y');
INSERT INTO elements VALUES( 15, 'P', 'Phosphorus', 30.9740, 3, '15', 'Y');
INSERT INTO elements VALUES( 16, 'S', 'Sulphur', 32.0650, 3, '16', 'Y');
INSERT INTO elements VALUES( 17, 'Cl', 'Chlorine', 35.4530, 3, '17', 'Y');
INSERT INTO elements VALUES( 18, 'Ar', 'Argon', 39.9480, 3, '18', 'Y');
The full table has 118 elements listed, of course.
Sample procedure
DROP PROCEDURE IF EXISTS lightweights;
CREATE PROCEDURE lightweights()
RETURNING INTEGER AS atomic_number, VARCHAR(3) AS symbol, VARCHAR(20) AS name;
DEFINE num INTEGER;
DEFINE sym VARCHAR(3);
DEFINE nam VARCHAR(20);
FOREACH SELECT e.atomic_number, e.symbol, e.name
INTO num, sym, nam
FROM elements AS e
WHERE atomic_number < 10
RETURN num, sym, nam WITH RESUME;
END FOREACH;
END PROCEDURE;
Example execution of the procedure to create a temp table
$ sqlcmd -d stores
SQL[3368]: select * from table(lightweights());
1|H |Hydrogen
2|He |Helium
3|Li |Lithium
4|Be |Beryllium
5|B |Boron
6|C |Carbon
7|N |Nitrogen
8|O |Oxygen
9|F |Fluorine
SQL[3368]: select * from table(lightweights()) into temp p32;;
SQL[3369]: select * from p32;
1|H |Hydrogen
2|He |Helium
3|Li |Lithium
4|Be |Beryllium
5|B |Boron
6|C |Carbon
7|N |Nitrogen
8|O |Oxygen
9|F |Fluorine
SQL[3370]: q;
$
Note that in sufficiently recent versions of Informix, you can replace TEMP with STANDARD or RAW to create a permanent table instead of a temporary table (and deleting TEMP is equivalent to replacing it with STANDARD). See SELECT statement > INTO table clauses.

SQL query for courses, semester and students

Hi I have a schema that looks like this
I was trying to make these 3 queries
Find the names of the top 4 instructors who have taught the most number of distinct courses. Display also the total number of courses taught.
Output columns: InstructorName, NumberOfCoursesTaught
Sort by: NumberOfCoursesTaught in descending order
Find the top 3 semesters in which the most number of courses were offered. (Treat Spring of 2009 and Spring of 2010 as two different semesters.
Output columns: Semester, Year, NumberOfCourses
Sort by: NumberOfCourses in descending order
Find the top 2 students who have taken the most number of courses.
Output columns: S_ID, StudentName, NumberOfCourses
Sort by: NumberOfCourses in descending order
For query 1 I wrote
Select name AS InstructorName, count(course_id) AS NumberOfCourses
from Teaches where name IN
(SELECT name FROM Instructor where Instructor.i_id = Teaches.i_id)
group by i_id
order by count(course_id) DESC;
For query 2
SELECT semester, year, count(course_id) as
NumberOfCourses from Takes WHERE year='2009'
group by semester, year
order by count(course_id) DESC;
For query 3
SELECT s_id as S_ID, name as StudentName, count(course_id) as NumberOfCourses
FROM Takes where name IN
(SELECT name from Student where Takes.s_id = Student.s_id)
group by s_id
order by count(course_id) DESC;
Query 1 and 3 give the error
ORA-00904: "NAME": invalid identifier
Query 2 is giving an output, but it's wrong. I need help making the 3 queries correct
Test Data is
tables file is
create table classroom (building varchar(15), room_number varchar(7), capacity numeric(4,0), primary key (building, room_number));
create table department (dept_name varchar(20), building varchar(15), budget numeric(12,2) check (budget > 0), primary key (dept_name));
create table course (course_id varchar(8), title varchar(50), dept_name varchar(20), credits numeric(2,0) check (credits > 0),
primary key(course_id));
create table instructor (i_ID varchar(5), name varchar(20) not null, dept_name varchar(20), salary numeric(8,2) check (salary > 29000), primary key (i_ID));
create table section (course_id varchar(8), sec_id varchar(8), semester varchar(6) check (semester in ('Fall', 'Winter', 'Spring', 'Summer')), year numeric(4,0) check (year > 1701 and year < 2100), building varchar(15), room_number varchar(7), time_slot_id varchar(4), primary key (course_id, sec_id, semester, year));
create table teaches (i_ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), primary key (i_ID, course_id, sec_id, semester, year));
create table student (s_ID varchar(5), name varchar(20) not null, dept_name varchar(20), tot_cred numeric(3,0) check (tot_cred >= 0), primary key (s_ID));
create table takes (s_ID varchar(5), course_id varchar(8), sec_id varchar(8), semester varchar(6), year numeric(4,0), grade varchar(2), primary key (s_ID, course_id, sec_id, semester, year));
create table advisor (s_ID varchar(5), i_ID varchar(5), primary key (s_ID));
create table time_slot (time_slot_id varchar(4), day varchar(1),start_hr numeric(2) check (start_hr >= 0 and start_hr < 24), start_min numeric(2) check (start_min >= 0 and start_min < 60), end_hr numeric(2) check (end_hr >= 0 and end_hr < 24), end_min numeric(2) check(end_min >= 0 and end_min < 60), primary key (time_slot_id, day, start_hr, start_min));
create table prereq (course_id varchar(8), prereq_id varchar(8), primary key (course_id, prereq_id));
create table grade_points(grade varchar(2), points Number(10,4), primary key (grade));
data file is
delete from prereq;
delete from time_slot;
delete from advisor;
delete from takes;
delete from student;
delete from teaches;
delete from section;
delete from instructor;
delete from course;
delete from department;
delete from classroom;
-- Classroom
insert into classroom values ('Packard', '101', '500');
insert into classroom values ('Painter', '514', '10');
insert into classroom values ('Taylor', '3128', '70');
insert into classroom values ('Watson', '100', '30');
insert into classroom values ('Watson', '120', '50');
-- Department
insert into department values ('Biology', 'Watson', '90000');
insert into department values ('Comp. Sci.', 'Taylor', '100000');
insert into department values ('Elec. Eng.', 'Taylor', '85000');
insert into department values ('Finance', 'Painter', '120000');
insert into department values ('History', 'Painter', '50000');
insert into department values ('Music', 'Packard', '80000');
insert into department values ('Physics', 'Watson', '70000');
-- Course
insert into course values ('BIO-101', 'Intro. to Biology', 'Biology', '4');
insert into course values ('BIO-301', 'Genetics', 'Biology', '4');
insert into course values ('BIO-399', 'Computational Biology', 'Biology', '3');
insert into course values ('CS-101', 'Intro. to Computer Science', 'Comp. Sci.', '4');
insert into course values ('CS-190', 'Game Design', 'Comp. Sci.', '4');
insert into course values ('CS-315', 'Robotics', 'Comp. Sci.', '3');
insert into course values ('CS-319', 'Image Processing', 'Comp. Sci.', '3');
insert into course values ('CS-347', 'Database System Concepts', 'Comp. Sci.', '3');
insert into course values ('EE-181', 'Intro. to Digital Systems', 'Elec. Eng.', '3');
insert into course values ('FIN-201', 'Investment Banking', 'Finance', '3');
insert into course values ('HIS-351', 'World History', 'History', '3');
insert into course values ('MU-199', 'Music Video Production', 'Music', '3');
insert into course values ('PHY-101', 'Physical Principles', 'Physics', '4');
-- Instructor
insert into instructor values ('10101', 'Srinivasan', 'Comp. Sci.', '65000');
insert into instructor values ('12121', 'Wu', 'Finance', '90000');
insert into instructor values ('15151', 'Mozart', 'Music', '40000');
insert into instructor values ('22222', 'Einstein', 'Physics', '95000');
insert into instructor values ('32343', 'El Said', 'History', '60000');
insert into instructor values ('33456', 'Gold', 'Physics', '87000');
insert into instructor values ('45565', 'Katz', 'Comp. Sci.', '75000');
insert into instructor values ('58583', 'Califieri', 'History', '62000');
insert into instructor values ('76543', 'Singh', 'Finance', '80000');
insert into instructor values ('76766', 'Crick', 'Biology', '72000');
insert into instructor values ('83821', 'Brandt', 'Comp. Sci.', '92000');
insert into instructor values ('98345', 'Kim', 'Elec. Eng.', '80000');
-- Section
insert into section values ('BIO-101', '1', 'Summer', '2009', 'Painter', '514', 'B');
insert into section values ('BIO-301', '1', 'Summer', '2010', 'Painter', '514', 'A');
insert into section values ('CS-101', '1', 'Fall', '2009', 'Packard', '101', 'H');
insert into section values ('CS-101', '1', 'Spring', '2010', 'Packard', '101', 'F');
insert into section values ('CS-190', '1', 'Spring', '2009', 'Taylor', '3128', 'E');
insert into section values ('CS-190', '2', 'Spring', '2009', 'Taylor', '3128', 'A');
insert into section values ('CS-315', '1', 'Spring', '2010', 'Watson', '120', 'D');
insert into section values ('CS-319', '1', 'Spring', '2010', 'Watson', '100', 'B');
insert into section values ('CS-319', '2', 'Spring', '2010', 'Taylor', '3128', 'C');
insert into section values ('CS-347', '1', 'Fall', '2009', 'Taylor', '3128', 'A');
insert into section values ('EE-181', '1', 'Spring', '2009', 'Taylor', '3128', 'C');
insert into section values ('FIN-201', '1', 'Spring', '2010', 'Packard', '101', 'B');
insert into section values ('HIS-351', '1', 'Spring', '2010', 'Painter', '514', 'C');
insert into section values ('MU-199', '1', 'Spring', '2010', 'Packard', '101', 'D');
insert into section values ('PHY-101', '1', 'Fall', '2009', 'Watson', '100', 'A');
-- Teaches
insert into teaches values ('10101', 'CS-101', '1', 'Fall', '2009');
insert into teaches values ('10101', 'CS-315', '1', 'Spring', '2010');
insert into teaches values ('10101', 'CS-347', '1', 'Fall', '2009');
insert into teaches values ('12121', 'FIN-201', '1', 'Spring', '2010');
insert into teaches values ('15151', 'MU-199', '1', 'Spring', '2010');
insert into teaches values ('22222', 'PHY-101', '1', 'Fall', '2009');
insert into teaches values ('32343', 'HIS-351', '1', 'Spring', '2010');
insert into teaches values ('45565', 'CS-101', '1', 'Spring', '2010');
insert into teaches values ('45565', 'CS-319', '1', 'Spring', '2010');
insert into teaches values ('76766', 'BIO-101', '1', 'Summer', '2009');
insert into teaches values ('76766', 'BIO-301', '1', 'Summer', '2010');
insert into teaches values ('83821', 'CS-190', '1', 'Spring', '2009');
insert into teaches values ('83821', 'CS-190', '2', 'Spring', '2009');
insert into teaches values ('83821', 'CS-319', '2', 'Spring', '2010');
insert into teaches values ('98345', 'EE-181', '1', 'Spring', '2009');
-- Student
insert into student values ('00128', 'Zhang', 'Comp. Sci.', '102');
insert into student values ('12345', 'Shankar', 'Comp. Sci.', '32');
insert into student values ('19991', 'Brandt', 'History', '80');
insert into student values ('23121', 'Chavez', 'Finance', '110');
insert into student values ('44553', 'Peltier', 'Physics', '56');
insert into student values ('45678', 'Levy', 'Physics', '46');
insert into student values ('54321', 'Williams', 'Comp. Sci.', '54');
insert into student values ('55739', 'Sanchez', 'Music', '38');
insert into student values ('70557', 'Snow', 'Physics', '0');
insert into student values ('76543', 'Brown', 'Comp. Sci.', '58');
insert into student values ('76653', 'Aoi', 'Elec. Eng.', '60');
insert into student values ('98765', 'Bourikas', 'Elec. Eng.', '98');
insert into student values ('98988', 'Tanaka', 'Biology', '120');
-- Takes
insert into takes values ('00128', 'CS-101', '1', 'Fall', '2009', 'A');
insert into takes values ('00128', 'CS-347', '1', 'Fall', '2009', 'A-');
insert into takes values ('12345', 'CS-101', '1', 'Fall', '2009', 'C');
insert into takes values ('12345', 'CS-190', '2', 'Spring', '2009', 'A');
insert into takes values ('12345', 'CS-315', '1', 'Spring', '2010', 'A');
insert into takes values ('12345', 'CS-347', '1', 'Fall', '2009', 'A');
insert into takes values ('19991', 'HIS-351', '1', 'Spring', '2010', 'B');
insert into takes values ('23121', 'FIN-201', '1', 'Spring', '2010', 'C+');
insert into takes values ('44553', 'PHY-101', '1', 'Fall', '2009', 'B-');
insert into takes values ('45678', 'CS-101', '1', 'Fall', '2009', 'F');
insert into takes values ('45678', 'CS-101', '1', 'Spring', '2010', 'B+');
insert into takes values ('45678', 'CS-319', '1', 'Spring', '2010', 'B');
insert into takes values ('54321', 'CS-101', '1', 'Fall', '2009', 'A-');
insert into takes values ('54321', 'CS-190', '2', 'Spring', '2009', 'B+');
insert into takes values ('55739', 'MU-199', '1', 'Spring', '2010', 'A-');
insert into takes values ('76543', 'CS-101', '1', 'Fall', '2009', 'A');
insert into takes values ('76543', 'CS-319', '2', 'Spring', '2010', 'A');
insert into takes values ('76653', 'EE-181', '1', 'Spring', '2009', 'C');
insert into takes values ('98765', 'CS-101', '1', 'Fall', '2009', 'C-');
insert into takes values ('98765', 'CS-315', '1', 'Spring', '2010', 'B');
insert into takes values ('98988', 'BIO-101', '1', 'Summer', '2009', 'A');
insert into takes values ('98988', 'BIO-301', '1', 'Summer', '2010', null);
-- Advisor
insert into advisor values ('00128', '45565');
insert into advisor values ('12345', '10101');
insert into advisor values ('23121', '76543');
insert into advisor values ('44553', '22222');
insert into advisor values ('45678', '22222');
insert into advisor values ('76543', '45565');
insert into advisor values ('76653', '98345');
insert into advisor values ('98765', '98345');
insert into advisor values ('98988', '76766');
-- Time_slot
insert into time_slot values ('A', 'M', '8', '0', '8', '50');
insert into time_slot values ('A', 'W', '8', '0', '8', '50');
insert into time_slot values ('A', 'F', '8', '0', '8', '50');
insert into time_slot values ('B', 'M', '9', '0', '9', '50');
insert into time_slot values ('B', 'W', '9', '0', '9', '50');
insert into time_slot values ('B', 'F', '9', '0', '9', '50');
insert into time_slot values ('C', 'M', '11', '0', '11', '50');
insert into time_slot values ('C', 'W', '11', '0', '11', '50');
insert into time_slot values ('C', 'F', '11', '0', '11', '50');
insert into time_slot values ('D', 'M', '13', '0', '13', '50');
insert into time_slot values ('D', 'W', '13', '0', '13', '50');
insert into time_slot values ('D', 'F', '13', '0', '13', '50');
insert into time_slot values ('E', 'T', '10', '30', '11', '45 ');
insert into time_slot values ('E', 'R', '10', '30', '11', '45 ');
insert into time_slot values ('F', 'T', '14', '30', '15', '45 ');
insert into time_slot values ('F', 'R', '14', '30', '15', '45 ');
insert into time_slot values ('G', 'M', '16', '0', '16', '50');
insert into time_slot values ('G', 'W', '16', '0', '16', '50');
insert into time_slot values ('G', 'F', '16', '0', '16', '50');
insert into time_slot values ('H', 'W', '10', '0', '12', '30');
-- Prereq
insert into prereq values ('BIO-301', 'BIO-101');
insert into prereq values ('BIO-399', 'BIO-101');
insert into prereq values ('CS-190', 'CS-101');
insert into prereq values ('CS-315', 'CS-101');
insert into prereq values ('CS-319', 'CS-101');
insert into prereq values ('CS-347', 'CS-101');
insert into prereq values ('EE-181', 'PHY-101');
-- Grade_points
insert into grade_points values ('A+', 4.0);
insert into grade_points values ('A', 4.0);
insert into grade_points values ('A-', 3.7);
insert into grade_points values ('B+', 3.3);
insert into grade_points values ('B', 3.0);
insert into grade_points values ('B-', 2.7);
insert into grade_points values ('C+', 2.3);
insert into grade_points values ('C', 2.0);
insert into grade_points values ('C-', 1.7);
insert into grade_points values ('D+', 1.3);
insert into grade_points values ('D', 1.0);
insert into grade_points values ('D-', 0.7);
insert into grade_points values ('F', 0.0);
insert into grade_points values ('NP', 0.0);
insert into grade_points values ('U', 0.0);
Expected Query 1:
Srinivasan 3
Brandt 2
Crick 2
Katz 2
My result of Query 2:
Fall 2009 9
Spring 2009 3
Summer 2009 1
Expected Query 2:
Spring 2010 7
Spring 2009 3
Fall 2009 3
Expected Query 3:
12345 Shankar 4
45678 Levy 3
I cant give you the full solution because you still learning. But here are some guide lines.
First one:
Select name AS InstructorName, count(course_id) AS NumberOfCourses
from Teaches where name IN ....
Teaches doesn't have name, instead of WHERE you need JOIN to Instructor table
Second one:
You dont need filter WHERE year='2009' what they ask is you GROUP BY year, semester if you do GROUP BY semester then all Spring semester will be on the same group
Third one: Same as first. You need JOIN to STUDENTS

SQL Server : creating a top 3 view - having difficulties

This is my first time asking a SQL related question. I am having a difficult time getting this query to work.
Basically, I have a database that has 3 tables Course, Faculty and Adjunct. This query is supposed to create a view named Top3Enrollment that returns FirstName, LastName, TotalStudents, and MaxEnrollment of the 3 faculty members with the largest total enrollment for their courses, along with the highest enrollment among the classes they teach.
When attempting to write the query I get an error with selecting the column FirstName
My query:
CREATE VIEW Top3Enrollment
AS
SELECT TOP 3 PERCENT
FirstName, LastName, SUM(Enrollment), MAX(Enrollment)
FROM
Faculty
JOIN
Course ON Faculty.Faculty_ID = Course.Faculty_ID
ORDER BY
MAX(Enrollment);
The error I get is:
Msg 8120, Level 16, State 1, Procedure Top3Enrollment, Line 3 [Batch Start Line 0]
Column 'Faculty.FirstName' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
My database structures:
CREATE TABLE Faculty
(
Faculty_ID VARCHAR(2),
LastName VARCHAR(20),
FirstName VARCHAR(20),
Department VARCHAR(10),
Campus VARCHAR(10)
);
INSERT INTO Faculty
VALUES ('1', 'Brown', 'Joe', 'Business', 'Kent'),
('2', 'Smith', 'John', 'Economics', 'Kent'),
('3', 'Jones', 'Sally', 'English', 'South'),
('4', 'Black', 'Bill', 'Economics', 'Deerwood'),
('5', 'Green', 'Gene', 'Business', 'South');
CREATE TABLE Course
(
Course_ID CHAR(2),
Ref_Number CHAR(5),
Faculty_ID VARCHAR(2),
Term Char(1),
BegDate SMALLDATETIME,
Enrollment INTEGER,
TotRev FLOAT
);
INSERT INTO Course
VALUES ('1', '12345', 'a', 'A', '2016-01-08 00:00:00', 24, 12345.32 ),
('2', '54321', '3', 'B', '2016-02-04 00:00:00', 18, 21435.51 ),
('3', '13524', '1', 'B', '2016-02-04 00:00:00', 7, 1256.67 ),
('4', '24653', '1', 'C', '2016-03-04 00:00:00', 29, 54421.11 ),
('5', '98765', '5', 'A', '2016-01-08 00:00:00', 35, 246753.23),
('6', '14862', '2', 'B', '2016-02-04 00:00:00', 14, 9876.87),
('7', '96032', '1', 'C', '2016-03-04 00:00:00', 8, 863159.31),
('8', '81256', '5', 'A', '2016-01-08 00:00:00', 5, 98762.14),
('9', '64321', '2', 'C', '2016-03-04 00:00:00', 23, 2965.98),
('10','90908', 'a', 'A', '2016-01-08 00:00:00', 45, 91724.02),
('11','90908', '3', 'A', '2016-01-08 00:00:00', 23, 73725.77),
('12','90908', '3', 'A', '2016-01-08 00:00:00', 16, 84224.29),
('13','90908', 'b', 'A', '2016-01-08 00:00:00', 13, 42719.82);
CREATE TABLE Adjuncts
(
Faculty_ID Char(2),
LastName VARCHAR(20),
FirstName VARCHAR(20),
Department VARCHAR(10),
Campus VARCHAR(10)
);
INSERT INTO Adjuncts
VALUES ('a', 'Rogers', 'Aaron', 'Business', 'Kent'),
('b', 'Manning', 'Peyton', 'Economics', 'North'),
('c', 'Drew', 'Maurice', 'English', 'Cecil'),
('d', 'Griffin', 'Robert', 'Music', 'Deerwood'),
('e', 'Goodell', 'Roger', 'Economics', 'South'),
('f', 'Vilma', 'Jonathan', 'Business', 'Kent');
Note:
I Understand I cannot have Order By but I wouldn't know what else to use
Added the database code
When you use aggregate functions like sum and max together with other columns you need to group your aggregations by those other columns.
Add GROUP BY like this
SELECT TOP 3 PERCENT FirstName, LastName, SUM(Enrollment), MAX(Enrollment)
FROM Faculty
JOIN Course ON Faculty.Faculty_ID = Course.Faculty_ID
GROUP BY FirstName, LastName
ORDER BY MAX(Enrollment);

Find average number of views before first lead event happens

create table events (
fk_user integer,
event varchar(40),
time integer
);
Insert into events (fk_user, event, time)
VALUES
('1', 'view', '1'),
('1', 'view', '3'),
('1', 'view', '4'),
('1', 'lead', '5'),
('1', 'view', '6'),
('1', 'view', '7'),
('1', 'lead', '9'),
('2', 'view', '1'),
('2', 'lead', '2'),
('2', 'lead', '3'),
('2', 'view', '6'),
('2', 'view', '7'),
('2', 'view', '8'),
('5', 'view', '1'),
('5', 'view', '2'),
('2', 'view', '4'),
('2', 'lead', '5'),
('2', 'view', '9');
What I am trying to find is: There are 3 'views' before a 'lead' occurs from the top. I want to take the average of the 'time' of first three occurrences. Is it possible to do with the window function ?
Expected output should be: (1+3+4)/3 = 2.666 (If taken integer then 3)
You can use the min window function along with a case statement to find the first_lead_time per fkuser and then use a derived table to get the average value of the views rows that become before the first_lead_time
select fkuser, avg(time) from (
select * ,
min (case when event = 'lead' then time end) over (partition by fkuser) as first_lead_time
from events
) t where time < first_lead_time
and event = 'view'
group by fkuser
Another way
select e.fk_user, avg(e.time)
from events e
join (
select min(time) first_lead_time, fkuser
from events
where event = 'lead'
group by fkuser
) t on t.fkuser = e.fkuser
where e.time < t.first_lead_time
group by e.fkuser