Advertisement
vlad0

04.AdvancedSQL-AllTasks

Jul 11th, 2013
543
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
SQL 11.50 KB | None | 0 0
  1. USE [TelerikAcademy]
  2. -- 01.Write a SQL query to find the names and salaries of the employees that take
  3. -- the minimal salary in the company. Use a nested SELECT statement.
  4.  
  5. SELECT FirstName, LastName, Salary
  6. FROM Employees
  7. WHERE Salary =
  8.     (SELECT MIN(Salary) FROM Employees)
  9.  
  10. -- 02. Write a SQL query to find the names and salaries of the employees that have
  11. -- a salary that is up to 10% higher than the minimal salary for the company.
  12.  
  13. SELECT FirstName, LastName, Salary
  14. FROM Employees
  15. WHERE Salary <=
  16.     (SELECT MIN(Salary) FROM Employees) * 1.1
  17. ORDER BY Salary DESC
  18.  
  19. -- 03. Write a SQL query to find the full name, salary and department of the employees
  20. -- that take the minimal salary in their department. Use a nested SELECT statement.
  21.  
  22. SELECT FirstName, LastName, Salary, DepartmentID
  23. FROM Employees e
  24. WHERE Salary =
  25.         (
  26.             SELECT MIN(Salary)
  27.             FROM Employees
  28.             WHERE DepartmentID = e.DepartmentID
  29.         )
  30.  
  31. -- 04. Write a SQL query to find the average salary in the department #1.
  32. SELECT AVG(Salary) AS AverageSalary
  33. FROM Employees
  34. WHERE DepartmentID = 1
  35.  
  36. -- 05. Write a SQL query to find the average salary  in the "Sales" department.
  37. SELECT AVG(e.Salary) AS AverageSalary
  38. FROM Employees e
  39.     JOIN Departments d
  40.     ON e.DepartmentID = d.DepartmentID
  41. WHERE d.Name = 'Engineering'
  42.  
  43. -- 06. Write a SQL query to find the number of employees in the "Sales" department.
  44. SELECT COUNT(*) AS EmployeesCount, d.Name AS Department-- it could be COUNT(e.FirstName)
  45. FROM Employees e
  46. JOIN Departments d
  47.     ON e.DepartmentID = d.DepartmentID
  48. WHERE d.Name = 'Sales'
  49. GROUP BY d.Name
  50.  
  51. -- 07. Write a SQL query to find the number of all employees that have manager.
  52. SELECT COUNT(*) AS EmployeesCount
  53. FROM Employees
  54. WHERE ManagerID IS NOT NULL
  55.  
  56. -- 08. Write a SQL query to find the number of all employees that have no manager.
  57. SELECT COUNT(*) AS EmployeesCount
  58. FROM Employees
  59. WHERE ManagerID IS NULL
  60.  
  61. -- 09.Write a SQL query to find all departments and the average salary for each of them.
  62. SELECT DepartmentID, AVG(Salary)
  63. FROM Employees
  64. GROUP BY DepartmentID
  65.  
  66. -- 10. Write a SQL query to find the count of all employees in each department and for
  67. -- each town.
  68. SELECT  DepartmentID, COUNT(*) AS EmployeesCount, t.Name
  69. FROM Employees e
  70.     JOIN Addresses a
  71.     ON a.AddressID = e.AddressID
  72.     JOIN Towns t
  73.     ON a.TownID = t.TownID
  74. GROUP BY e.DepartmentID, t.Name
  75. ORDER BY e.DepartmentID
  76.  
  77. -- 11. Write a SQL query to find all managers that have exactly 5 employees. Display their
  78. -- first name and last name.
  79. SELECT e.FirstName, e.LastName, e.EmployeeID
  80. FROM Employees e
  81. WHERE 5 =
  82.         (
  83.             SELECT COUNT(*)
  84.             FROM Employees
  85.             WHERE ManagerID = e.EmployeeID
  86.         )
  87.  
  88. -- 12. Write a SQL query to find all employees along with their managers. For employees
  89. -- that do not have manager display the value "(no manager)".
  90.  
  91. SELECT e.FirstName, e.LastName,  ISNULL(m.FirstName+' '+m.LastName, 'no manager') AS ManagerFullName
  92. FROM Employees m
  93.     RIGHT JOIN Employees e
  94.     ON e.ManagerID = m.EmployeeID
  95.  
  96. -- 13. Write a SQL query to find the names of all employees whose last name is
  97. -- exactly 5 characters long. Use the built-in LEN(str) function.
  98.  
  99. SELECT e.FirstName, e.LastName
  100. FROM Employees e
  101. WHERE LEN(e.LastName) = 5
  102.  
  103. -- 14. Write a SQL query to display the current date and time in the following
  104. -- format "day.month.year hour:minutes:seconds:milliseconds". Search in  Google to
  105. -- find how to format dates in SQL Server
  106. SELECT  CONVERT(VARCHAR(25), GETDATE(), 131) AS [DATE]
  107. SELECT  CONVERT(VARCHAR(25), GETDATE(), 121) AS [DATE]
  108.  
  109. -- 15. Write a SQL statement to create a table Users. Users should have
  110. -- username, password, full name and last login time. Choose appropriate data types
  111. -- for the table fields. Define a primary key column with a primary key constraint. Define
  112. -- the primary key column as identity to facilitate inserting records. Define unique
  113. -- constraint to avoid repeating usernames. Define a check constraint to ensure the
  114. -- password is at least 5 characters long.
  115.  
  116. -- username, password, fullname, lastlogin
  117. CREATE TABLE Users
  118.     (
  119.         UserID INT PRIMARY KEY IDENTITY(1,1) NOT NULL,
  120.         Username nvarchar(20) UNIQUE NOT NULL,
  121.         [Password] nvarchar(20) CHECK(LEN([Password]) > 4) NOT NULL,
  122.         Fullname nvarchar(100) NOT NULL,
  123.         LastLogin datetime
  124.     )
  125.  
  126. -- 16. Write a SQL statement to create a view that displays the users from
  127. -- the Users table that have been in the system today. Test if the view works correctly.
  128. CREATE VIEW RecentUsers
  129. AS
  130.     SELECT Username, DAY(GETDATE() - LastLogin) AS DayDifference
  131.     FROM Users
  132.     WHERE DAY(GETDATE() - LastLogin) = 1
  133.  
  134. -- 17. Write a SQL statement to create a table Groups. Groups should have
  135. -- unique name (use unique constraint). Define primary key and identity column
  136. CREATE TABLE Groups
  137.         (
  138.             GroupID INT PRIMARY KEY IDENTITY(1,1),
  139.             Name nvarchar(20) UNIQUE
  140.         )
  141.  
  142. -- 18. Write a SQL statement to add a column GroupID to the table Users. Fill some
  143. -- data in this new column and as well in the Groups table. Write a SQL statement to
  144. -- add a foreign key constraint between tables Users and Groups tables.
  145. ALTER TABLE Users
  146.     ADD GroupID INT
  147.  
  148. ALTER TABLE Users
  149.     ADD CONSTRAINT FK_UsersGroup FOREIGN KEY(GroupID) REFERENCES Groups(GroupID)
  150.  
  151. -- 19. Write SQL statements to insert several records in the Users and
  152. -- Groups tables.
  153. INSERT INTO Groups
  154. VALUES('Students')
  155.  
  156. INSERT INTO Groups
  157. VALUES('Proffessors')
  158.  
  159. INSERT INTO Groups
  160. VALUES('Administrators')
  161.  
  162. INSERT INTO Users
  163. VALUES
  164.     ('student1', 'student1pass', 'Studentov-1', GETDATE(), 2),
  165.     ('student2', 'student2pass', 'Studentov-2', GETDATE(), 1),
  166.     ('student3', 'student3pass', 'Studentov-3', GETDATE(), 1)
  167.  
  168. -- 20. Write SQL statements to update some of the records in the
  169. -- Users and Groups tables.
  170.  
  171. UPDATE Users
  172. SET Username = 'studentche2', Password = 'studentche2pass'
  173. FROM Users
  174. WHERE Username = 'student1'
  175.  
  176. UPDATE Users
  177. SET Username = 'student1', Password = 'student1pass'
  178. FROM Users
  179. WHERE Username = 'studentche2'
  180.  
  181. UPDATE Groups
  182. SET Name = 'Uchenici'
  183. FROM Groups
  184. WHERE GroupID = 1
  185.  
  186. UPDATE Groups
  187. SET Name = 'Students'
  188. FROM Groups
  189. WHERE GroupID = 1
  190.  
  191. -- 21. Write SQL statements to delete some of the records from the Users and
  192. -- Groups tables.
  193. BEGIN TRAN
  194.  
  195. DELETE FROM Users
  196. WHERE Username = 'student2'
  197.  
  198. DELETE FROM Users
  199. WHERE UserID = 8
  200.  
  201. -- all users from connected with the group should be deleted
  202. DELETE FROM Groups
  203. WHERE GroupID = 3
  204.  
  205. ROLLBACK TRAN
  206.  
  207. -- 22. Write SQL statements to insert in the Users table the names of all
  208. -- employees from the Employees table. Combine the first and last names as a
  209. -- full name. For username use the first letter of the first name + the
  210. -- last name (in lowercase). Use the same for the password, and NULL for
  211. -- last login time.
  212.  
  213. -- there are duplicate if we get the only the first letter from the FirstName
  214. -- so I make the username with the first 3 letters
  215. INSERT INTO Users(Username, [Password], Fullname, GroupID)
  216. SELECT  LOWER(LEFT(FirstName,3)+LastName),
  217.         LOWER(LEFT(FirstName,3)+LastName),
  218.         FirstName+' ' + LastName,
  219.         1
  220. FROM Employees
  221.  
  222. -- 23. Write a SQL statement that changes the password to NULL for
  223. -- all users that have not been in the system since 10.03.2010.
  224.  
  225. UPDATE Users
  226. SET [Password] = NULL
  227. FROM Users
  228. WHERE   LastLogin < CONVERT(datetime, '10-03-2010')
  229.         AND [Password] IS NOT NULL
  230.  
  231. -- 24. Write a SQL statement that deletes all users without
  232. -- passwords (NULL password).
  233.  
  234. BEGIN TRAN
  235. DELETE FROM Users
  236. WHERE [Password] IS NULL
  237.  
  238. ROLLBACK TRAN
  239.  
  240. -- 25. Write a SQL query to display the average employee salary by
  241. -- department and job title.
  242.  
  243. SELECT AVG(e.Salary) AS [AverageSalary], e.JobTitle, d.Name
  244. FROM Employees e
  245.     JOIN Departments d
  246.     ON e.DepartmentID = d.DepartmentID
  247. GROUP BY JobTitle, d.Name
  248. ORDER BY [AverageSalary] DESC
  249.  
  250. -- 26. Write a SQL query to display the minimal employee salary by
  251. -- department and job title along with the name of some of the
  252. -- employees that take it.
  253.  
  254. SELECT e.FirstName+' '+e.LastName AS FullName, e.Salary, e.JobTitle, d.Name
  255. FROM Employees e
  256.     JOIN Departments d
  257.     ON e.DepartmentID = d.DepartmentID
  258. GROUP BY e.JobTitle, d.Name, e.Salary,  e.FirstName+' '+e.LastName, e.DepartmentID
  259. HAVING e.Salary =
  260.     (
  261.         SELECT MIN(Salary)
  262.         FROM Employees
  263.         -- should check MIN(Salary) by JobTitle AND DepartmentID
  264.         WHERE JobTitle = e.JobTitle AND DepartmentID = e.DepartmentID
  265.     )
  266. ORDER BY e.Salary DESC
  267.  
  268.  
  269. -- 27. Write a SQL query to display the town where
  270. -- maximal number of employees work.
  271.  
  272. SELECT TOP(1) t.Name, COUNT(e.EmployeeID) AS WorkingEmployees
  273. FROM Towns t
  274.     JOIN Addresses a
  275.     ON t.TownID = a.TownID
  276.     JOIN Employees e
  277.     ON e.AddressID = a.AddressID
  278. GROUP BY t.Name
  279. ORDER BY WorkingEmployees DESC
  280.  
  281. -- 28. Write a SQL query to display the number of
  282. -- managers from each town.
  283.  
  284. SELECT COUNT(DISTINCT e.ManagerID), t.Name
  285. FROM Employees e
  286.     JOIN Employees m
  287.     ON e.ManagerID = m.EmployeeID
  288.     JOIN Addresses a
  289.     ON a.AddressID = m.AddressID
  290.     JOIN Towns t
  291.     ON a.TownID = t.TownID
  292. GROUP BY t.Name
  293.  
  294. -- 29. Write a SQL to create table WorkHours to store work
  295. -- reports for each employee (employee id, date, task, hours,
  296. -- comments). Don't forget to define  identity, primary key and
  297. -- appropriate foreign key.
  298. -- Issue few SQL statements to insert, update and delete of
  299. -- some data in the table.
  300. -- Define a table WorkHoursLogs to track all changes in the
  301. -- WorkHours table with triggers. For each change keep the old
  302. -- record data, the new record data and the command
  303. -- (insert / update / delete).
  304.  
  305. CREATE TABLE Tasks
  306.         (
  307.             TaskID INT IDENTITY(1,1) PRIMARY KEY,
  308.             NAME nvarchar(50) NOT NULL
  309.         )
  310.  
  311. CREATE TABLE WorkHours 
  312.         (
  313.             WorkHoursID INT IDENTITY(1,1) PRIMARY KEY,
  314.             EmployeeID INT FOREIGN KEY(EmployeeID) REFERENCES Employees(EmployeeID) NOT NULL,
  315.             [DATE] datetime NOT NULL,
  316.             TaskID INT FOREIGN KEY(TaskID) REFERENCES Tasks(TaskID) NOT NULL,
  317.             [Hours] INT NULL,
  318.             Comments nvarchar(250) NULL,
  319.         )
  320.  
  321. INSERT INTO WorkHours
  322.     VALUES(5, '2013-07-12', 4, NULL, NULL)
  323.  
  324. CREATE TABLE WorkHoursLog
  325.         (
  326.             LogID INT IDENTITY(1,1) PRIMARY KEY,
  327.             ExecutedCommand nvarchar(20) NULL,
  328.             WorkHoursID INT NULL,
  329.             OldEmployeeID INT FOREIGN KEY(OldEmployeeID) REFERENCES Employees(EmployeeID) NULL,
  330.             [OldDate] datetime NULL,
  331.             OldTaskID INT FOREIGN KEY(OldTaskID) REFERENCES Tasks(TaskID) NULL,
  332.             [OldHours] INT NULL,
  333.             OldComments nvarchar(250) NULL,
  334.             NewEmployeeID INT FOREIGN KEY(NewEmployeeID) REFERENCES Employees(EmployeeID) NULL,
  335.             [NewDate] datetime NULL,
  336.             NewTaskID INT FOREIGN KEY(NewTaskID) REFERENCES Tasks(TaskID) NULL,
  337.             [NewHours] INT NULL,
  338.             NewComments nvarchar(250) NULL
  339.         )
  340.  
  341. ALTER TRIGGER TR_WorkHoursDelete
  342. ON WorkHours
  343. FOR DELETE
  344. AS
  345.     INSERT INTO WorkHoursLog
  346.     SELECT 'DELETE', *, NULL, NULL, NULL, NULL, NULL
  347.     FROM deleted
  348.  
  349. GO
  350.  
  351. ALTER TRIGGER TR_WorkHoursInsert
  352. ON WorkHours
  353. FOR INSERT
  354. AS
  355.     INSERT INTO WorkHoursLog
  356.     SELECT 'INSERT', WorkHoursID,NULL, NULL, NULL, NULL, NULL,
  357.         EmployeeID, [DATE], TaskID, [Hours], Comments
  358.     FROM inserted
  359.  
  360. GO
  361.  
  362. ALTER TRIGGER TR_WorkHoursUpdate
  363. ON WorkHours
  364. FOR UPDATE
  365. AS
  366.     INSERT INTO WorkHoursLog
  367.     SELECT 'UPDATE', d.WorkHoursID, d.EmployeeID, d.[DATE], d.TaskID, d.[Hours], d.Comments,
  368.     i.EmployeeID, i.[DATE], i.TaskID, i.[Hours], i.Comments  
  369.     FROM inserted i, deleted d
  370. GO
  371.  
  372.  
  373. -- TESTING TRIGGERS --
  374. DELETE FROM WorkHours WHERE WorkHoursID = 3
  375.  
  376. INSERT INTO WorkHours
  377.     VALUES(5, '2013-07-12', 4, NULL, NULL)
  378.  
  379. UPDATE WorkHours
  380. SET Hours = 123
  381. FROM WorkHours
  382. WHERE WorkHoursID = 8;
  383. -- END TESTING --
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement