0% found this document useful (0 votes)
30 views24 pages

SQL

The document contains scripts to create stored procedures and views to analyze data from tables in a database. The first stored procedure creates a view that summarizes data from multiple tables, including a user's total spending, number of days visited, and their first purchase each day. The second stored procedure handles inserting, updating, and deleting records from a sales table. It checks for existing records before inserting or updating, deletes duplicates, and uses triggers to log deleted records. Additional stored procedures and views are created to analyze visitor data by masking sensitive information, summarizing subjects taught by lecturers, and using dynamic SQL and pivoting to display the number of classes for each subject by lecturer.

Uploaded by

arjunnjha27
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
0% found this document useful (0 votes)
30 views24 pages

SQL

The document contains scripts to create stored procedures and views to analyze data from tables in a database. The first stored procedure creates a view that summarizes data from multiple tables, including a user's total spending, number of days visited, and their first purchase each day. The second stored procedure handles inserting, updating, and deleting records from a sales table. It checks for existing records before inserting or updating, deletes duplicates, and uses triggers to log deleted records. Additional stored procedures and views are created to analyze visitor data by masking sensitive information, summarizing subjects taught by lecturers, and using dynamic SQL and pivoting to display the number of classes for each subject by lecturer.

Uploaded by

arjunnjha27
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1/ 24

***********************************************************************************

*************************************************************
USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DDL_Q1] Script Date:


08-08-2023 10:45:36 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DDL_Q1]


AS
/*Q.1. Use the tables Product_details, Users, and Sales.

Create a non clustered index on Product_details table.


Also, Create a view to display Userid, Total Amount spent by each user,
how many days has each user visited the delivery app,
what was the first product purchased by each user each day.

(Tag: Views, Windows function, Joins, Indexing)

Please keep object name as follows:


View -> Vw_DDL_Q1

Sample Output :-
(Please keep same column names as below)

user_id totalAmt Days FirstproductID


12552 4.99 1 870
4159 93.48 1 928
9282 63.97 1 932
13112 1199.46 1 932
14312 253.90 4 884

*/

CREATE OR ALTER VIEW VW_DDL_Q1


AS
SELECT USER_ID user_id,TOTALAMT totalAmt,Days, PRODUCTID AS FirstproductID FROM(
SELECT A.USER_ID,A.TOTALAMT,Days,P.PRODUCTID,
ROW_NUMBER() OVER(PARTITION BY A.USER_ID ORDER BY S.ORDERDATE) RN
FROM
(
SELECT U.USER_ID
,SUM(P.LISTPRICE*S.ORDERQTY) TOTALAMT
,count(distinct cast(s.OrderDate as date)) as Days
FROM SALES S
JOIN USERS U ON S.USER_ID = U.USER_ID
JOIN PRODUCT_DETAILS P ON S.PRODUCTID = P.PRODUCTID
GROUP BY U.USER_ID
) A
JOIN SALES S ON S.USER_ID = A.USER_ID
JOIN USERS U ON S.USER_ID = U.USER_ID
JOIN PRODUCT_DETAILS P ON P.PRODUCTID = S.PRODUCTID
) B
WHERE RN = 1
GO

***********************************************************************************
*************************************************************
USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DDL_Q2] Script Date:


08-08-2023 12:41:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DDL_Q2]


AS
/*Q.2. Use the table Sales. Check the incoming data for sales table,
if the values of order_id, user_id, order date and product_id already
exists then create a stored procedure to update the value for order qty or
else insert the new incoming record in the table.
Delete the duplicate records if exists and create a trigger
to automatically insert that record in the table backupSales.
Also use non-clustered indexes to speed up query performance.

Use appropriate comments to explain the working of procedure.


Use proper naming conventions for each object that will clearly describe
what objects they are and maintain the code beauty
of the entire code.

(Tag: Creation of procs, Index, Triggers, Single line, and Multiline comments,
insert, update, delete)

Please keep object name as follows:


PROCEDURE -> SP_DDL_Q2
Trigger-> Trig_DDL_Q2
Backup table --> backupsales

Schema of backupsales table is as follows:


SalesOrderID|User_id|OrderDate|OrderQty|ProductID

Execute the SP using below inputs.


OrderID UserID OrderDate ProductID Qty
55520 12836 06-02-2023 888 3
55520 18803 06-02-2023 888 7
55521 12836 06-02-2023 477 4
55521 12836 06-02-2023 477 9
43659 1045 31-05-2011 709 6
69489 727 31-03-2014 883 2

*/

select * from Sales where SalesOrderID = 69489


GO

select ProductID from product_details


CREATE NONCLUSTERED INDEX IX_tblproduct_ID
ON product_details(ProductID ASC)

create table backupsales(


SalesOrderID int,
User_id int,
OrderDate date,
OrderQty int,
ProductID int)

create or alter proc SP_DDL_Q2


@SalesOrderID int
,@User_id int
,@OrderDate datetime
,@ProductID int
,@OrderQty smallint
as
begin

--deleted the duplicate records using cte table and inserted into backupsales table
using trigger
/*

TRIGGER
create or alter trigger Trig_DDL_Q2
on sales
AFTER Delete
AS
insert into backupsales select SalesOrderID,User_id,OrderDate,OrderQty,ProductID
from deleted
*/

/*
BACKUP SALES TABLE
create table backupsales(
SalesOrderID int,
User_id int,
OrderDate date,
OrderQty int,
ProductID int)
*/
with cte as(
select *,ROW_NUMBER() over(partition by SalesOrderID,ProductID order by ShipDate
desc) rn from Sales
)
delete from cte where rn > 1

--checked for order present in table


declare @flag int
set @flag = (select count(*) from Sales where ProductID = @ProductID and
SalesOrderID = @SalesOrderID and User_id = @User_id)

/*if order is present then updated the quantity of particular order*/


if(@flag = 1)
begin
update Sales set OrderQty = @OrderQty where ProductID = @ProductID and
SalesOrderID = @SalesOrderID
end
/* If new orders comes then it will be inserted into backup table*/
else
begin
insert into Sales(SalesOrderID,User_id,OrderDate,OrderQty,ProductID)
values(@SalesOrderID,@User_id,@OrderDate,@OrderQty,@ProductID)
end
end

exec SP_DDL_Q2 '44162','5304','2011-08-06','1','750'

create or alter trigger Trig_DDL_Q2


on sales
AFTER Delete
AS
insert into backupsales select SalesOrderID,User_id,OrderDate,OrderQty,ProductID
from deleted

select * from Sales where SalesOrderID = 69489

insert into sales values(69489,'6F48-4F2F-BC',727,'2014-03-31 20:41:22.000','2014-


04-07 00:00:00.000',2,883)

select * from backupsales

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DQL_Q1A] Script Date:


08-08-2023 15:04:19 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DQL_Q1A]


AS
/*Q.1.A. The table VISITS represents the visits of guest lecturers to the school.
The table shows the name of the lecturer, the floor number he/she visited and the
subjects he/she taught.
Create a view that displays in separate columns the lecturers first name, middle
name, last name, the most visited floor by that lecturer,
the total number of visits he/she made to the school and subjects taught by each
lecturer.
Subjects for each lecturer should be displayed in one field separated by comma.
(Output will have one record for each lecturer)

Create a new table VISITS_MASK which is an exact copy of VISITS table. Copy all
data from VISITS table into VISITS_MASK table.
VISITS_MASK table should be created in such a way that first three characters of
each subjects in the Subjects column should be masked.

(Tag: Joins, Group By, Window Functions, CTE, Rank, String Operations, Data
Masking)

Please keep object name as follows:


View -> VW_DQL_Q1A

OUTPUT SAMPLE

FirstName MiddleName LastName Most_Visited_Floor Total_Visits


Subjects
Daniel L Clark 1 3
HISTORY,SCIENCE
ELLY Smith 1 2
HISTORY,Maths
James C Gracia 2 3
HISTORY,SCIENCE
john W Thomas 3 4
ECONOMICS,Maths,SCIENCE
*/

GO

create or alter view VW_DQL_Q1A


as

with cte1 as(


select distinct name from VISITS
),
cte2 as(
select
left(name, charindex(' ', name) - 1) AS FirstName,
case
when len(name) - len(replace(name, ' ', '')) > 1 then substring(name, charindex('
', name) + 1, charindex(' ', name, charindex(' ', name) + 1) - charindex(' ', name)
- 1)
else ''
end as MiddleName,
case
when len(name) - len(replace(name, ' ', '')) > 1 then substring(name, charindex('
', name, charindex(' ', name) + 1) + 1, len(name))
else substring(name, charindex(' ', name) + 1, len(name))
end as LastName,
name from cte1
),
cte3 as(
select FirstName,MiddleName,LastName,v.FLOOR,c.name,STRING_AGG(v.SUBJECTS,',')
Subjects
,ROW_NUMBER() over(partition by c.name order by count(floor) desc) rn from cte2 c
join VISITS v on v.NAME like c.name
group by FirstName,MiddleName,LastName,c.name,v.FLOOR
)
select c.FirstName,c.MiddleName,c.LastName,c.FLOOR Most_Visited_Floor, COUNT(*)
Total_Visits, c.Subjects from cte3 c
join VISITS v on c.name = v.NAME
where rn = 1
group by c.FirstName,c.MiddleName,c.LastName,c.FLOOR,c.Subjects
select * from VW_DQL_Q1A

--mask table
select Name,LOCATION,FLOOR,CONCAT(REPLICATE('*', 3), SUBSTRING(subjects, 4,
LEN(SUBJECTS) - 3)) as Subjects into VISITS_MASK from VISITS

select * from VISITS_MASK

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DQL_Q1B] Script Date:


08-08-2023 15:04:07 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DQL_Q1B]


AS
/*Q.1.B. Refer table VISITS.
Create a parameterized procedure named sp_no_of_classes to show the number of
classes taken by each lecturer for each subject in the below format-
(Output) - (It should be only one record for each lecturer). Table name VISITS
and column names (subject n ames)
will be the input paramters of the stored procedure (shown in example below).
The input parameter column names should be comma seperated.
Execute the SP and Store the Output of the query in a table called
visits_no_of_classes.

Example (execute in the below format):


Exec [procname] VISITS,History,Economics,Maths,Science

Solve the prblem using dynamic SQL and pivot.


(Tag: Dynamic SQL, Pivot)

Sample OUTPUT :-

Name History Economics Maths Science


Daniel L Clark 2 0 0 1
Elly Smith 1 0 1 0

*/
GO

CREATE OR ALTER PROC sp_no_of_classes


@table_name VARCHAR(200),
@column_name VARCHAR(200)
AS
BEGIN
-- Get distinct subjects
DECLARE @Columns VARCHAR(MAX), @columns_select varchar(max);
with cte as(
SELECT DISTINCT subjects FROM visits
)
SELECT @Columns = STRING_AGG(SUBJECTS, ','),
@columns_select = STRING_AGG(CONCAT('isnull(',SUBJECTS,',0) as ',SUBJECTS),',')
FROM cte;
DECLARE @Query VARCHAR(MAX) =

'insert into visits_no_of_classes


SELECT NAME,' + @columns_select + ' FROM
(
SELECT NAME, ' + @column_name + ', COUNT(' + @column_name + ') as [count]
FROM ' + @table_name + ' GROUP BY Name,' + @column_name + '
) A
PIVOT(
SUM([count])
FOR ' + @column_name + '
IN (' + @Columns + ')
)
AS pivotTable';

EXEC(@Query);

END;

EXEC sp_no_of_classes 'visits', 'subjects';

select * from VISITS

create table visits_no_of_classes(


Name varchar(30)
,Economics int
,History int
,Maths int
,Science int)

select * from visits_no_of_classes

select * from VISITS

***********************************************************************************
*************************************************************
USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DQL_Q6] Script Date:


08-08-2023 17:32:15 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DQL_Q6]


AS
/*Q.6. Create a parameterised stored procedure sp_emp_hierarchy to generate below
hierarchy output using EMPLOYEE_MASTER table.
Create a table named HIERARCHY_OUTPUT with the . Pass the table name
HIERARCHY_OUTPUT as an input parameter and
store the result in HIERARCHY_OUTPUT table.
Employee Master has more than one employee who are not reporting to anyone and
they have no reportees.
The employees marked as SuperAdmin should also be included in the highest
category level.

You have to use below topics to implement solution:


Recursive CTE, join, Dynamic SQL, global temp tables.

You have a table [employee_master] with employee information.


Below given data are just sample records. You need to create the hierarchy of
the entire organization as mentioned in the employee_master table.

sample input:
EmployeeID Reporting To Email ID
HRM146 SuperAdmin tkala@celebaltech.com
HRM1997 NULL
pratik.singh@celebaltech.com
HRM1682 NULL ats@celebaltech.com
HRM42 Anirudh Kala HRM146
abhishek.parti@celebaltech.com
HRM31 Anirudh Kala HRM146
tushar.mittal@celebaltech.com
HRM27 Anirudh Kala HRM146
rohan.saini@celebaltech.com
HRM92 Tushar Mittal HRM31
muskan.khatnani@celebaltech.com
HRM87 Tushar Mittal HRM31
gaurav.modi@celebaltech.com
HRM86 Tushar Mittal HRM31
abhishek.jarwal@celebaltech.com
HRM393 Gaurav Modi HRM87
kanishk.shrotriya@celebaltech.com
HRM341 Gaurav Modi HRM87 jennet.john@celebaltech.com
HRM1764 Jennet John HRM341
aditi.bohra@celebaltech.com
HRM1746 Jennet John HRM341
chayan.sharma@celebaltech.com
HRM3253 Jennet John HRM341
kartik.yadav@celebaltech.com

Sample output (HIERARCHY_OUTPUT):

EmployeeID Reporting To Email ID


levels
HRM146 SuperAdmin tkala@celebaltech.com
1
HRM1997 NULL
pratik.singh@celebaltech.com 1
HRM1682 NULL ats@celebaltech.com
1
HRM42 Anirudh Kala HRM146
abhishek.parti@celebaltech.com 2
HRM31 Anirudh Kala HRM146
tushar.mittal@celebaltech.com 2
HRM27 Anirudh Kala HRM146
rohan.saini@celebaltech.com 2
HRM92 Tushar Mittal HRM31
muskan.khatnani@celebaltech.com 3
HRM87 Tushar Mittal HRM31
gaurav.modi@celebaltech.com 3
HRM86 Tushar Mittal HRM31
abhishek.jarwal@celebaltech.com 3
HRM393 Gaurav Modi HRM87
kanishk.shrotriya@celebaltech.com 4
HRM341 Gaurav Modi HRM87 jennet.john@celebaltech.com
4
HRM1764 Jennet John HRM341
aditi.bohra@celebaltech.com 5
HRM1746 Jennet John HRM341
chayan.sharma@celebaltech.com 5
HRM3253 Jennet John HRM341
kartik.yadav@celebaltech.com 5

(Tag: Recursive CTE, join, Dynamic SQL, global temp tables.)


*/
GO

create or alter proc sp_emp_hierarchy


@output_table varchar(max)
as
WITH RecursiveHierarchy AS (
SELECT
EmployeeID,
[Reporting To],
[Email ID],
1 AS Level
FROM
(select *,substring([Reporting To],charindex('HRM',[Reporting
To]),len([Reporting To])) [RM_HRM]from employee_master) e -- Replace with your
actual table name
WHERE
RM_HRM IS NULL

UNION ALL

SELECT
e.EmployeeID,
e.[Reporting To],
e.[Email ID],
rh.Level + 1
FROM
(select *,substring([Reporting To],charindex('HRM',[Reporting
To]),len([Reporting To])) [RM_HRM]from employee_master) e
JOIN
RecursiveHierarchy rh ON e.RM_HRM = rh.EmployeeID
),cte2 as(
SELECT
r.EmployeeID,
r.[Reporting To],
r.[Email ID],
r.Level
FROM
RecursiveHierarchy r
UNION ALL
SELECT
EmployeeID,
[Reporting To],
[Email ID],
2 AS Levels
FROM
(select *,substring([Reporting To],charindex('HRM',[Reporting
To]),len([Reporting To])) [RM_HRM]from employee_master) e
WHERE
EmployeeID NOT IN (SELECT DISTINCT EmployeeID FROM RecursiveHierarchy)

)
select * into #temp from cte2 ORDER BY Level;

declare @sql varchar(max)


set @sql = 'select * into '+@output_table+' from #temp'
exec(@sql)
drop table #temp

exec sp_emp_hierarchy 'HIERARCHY_OUTPUT'

select * from HIERARCHY_OUTPUT order by level

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob_DQL_Q7] Script Date:


08-08-2023 18:23:08 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob_DQL_Q7]


AS
/*Q.7. Create a stored procedure named sp_scd_type2 to load data from source to
target table.
Source table [emp_data] shows the salaries and other details of employees (Source
data shown below).
Create a target table emp_target (shown in Output below) tha t maintains all the
historical,
changed and new data if any in the source data. Also, maintain a Active flag (Y/N)
in the target table to show
if its current or historical data.
Use SCD type 2 to implement the same.

Source input:
eid ename esal edept
E201 David 40000 10
E202 Preeta 35000 20
E203 Kevin 63000 10
E204 George 58000 30
E205 Danny 71000 20

Once data is loaded from source to target ,


Please insert/update below records manually into the source table emp_data.
(Insert - if eid is new and update - if eid already exists.)

Load below data into source:


eid ename esal edept
E206 Rebecca 48000 10
E202 Preeta 46000 20
E205 Danny 71000 30

Above records should be updated in the target table in SCD type 2 method after
running the stored procedure.

Output Sample:

eid ename esal edept active


E204 George 58000 30 Y
E205 Danny 71000 20 N
E206 Rebecca 48000 10 Y
E205 Danny 71000 30 Y

(Tag: SCD Type2.)


*/
GO

select * from emp_data

create table emp_target (eid nvarchar(40), ename nvarchar(40), esal int, edept int,
Active nvarchar(40))

insert into emp_data values( 'E206','Rebecca',48000,10)


insert into emp_data values('E202','Preeta',46000,20)
insert into emp_data values('E205','Danny',71000,30)

-- create procedures

create or alter procedure sp_scd_type2


as
begin
insert into emp_target(eid,ename,esal,edept,Active)
select eid,ename,esal,edept,'Y'
from emp_data
where eid not in (select eid from emp_target);

update target set Active = 'N'


from emp_target as target
inner join emp_data as source
on target.eid = source.eid
where target.ename <> source.ename or target.esal <> source.esal or
target.edept <> source.edept;
insert into emp_target (eid,ename,esal,edept,Active)
select source.eid,source.ename,source.esal,source.edept, 'Y'
from emp_data as source
inner join emp_target as target
on source.eid = target.eid
where target.Active = 'N';

update source
set ename = target.ename, esal = target.esal, edept = target.edept
from emp_data as source
inner join emp_target as target
on source.eid = target.eid
where target.Active = 'Y';

end;

exec sp_scd_type2

select * from emp_target


select * from emp_data

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DDL_Q1] Script Date:


09-08-2023 10:34:47 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DDL_Q1]


AS
/*Q.1. Create a stored procedure to get the number of hours between two dates
having a DateTime format.
You should exclude all Sundays and 1st and 2nd Saturdays if it comes within the
date range.
If either of the input dates are Sunday or the 1st or 2nd Saturday, then include
that particular date too.
Stored procedure will have two input parameters - Start_Date and End_Date.
Execute your stored procedure only for the below dates and store the result in a
table named COUNTWORKINGHOURS
in the below format (Sample Output).
(Tag: Create Procedure, Date Functions)

Please keep object name as follows:


Procedure Name -> SP_COUNTWORKINGHOURS

Execute SP for below dates:


START_DATE END_DATE
2023-07-01 00:00 2023-07-17 00:00
2023-05-22 00:00 2023-06-04 00:00
2023-07-07 00:00 2023-07-08 23:00
2023-03-05 00:00 2023-03-26 00:00
2023-07-12 00:00 2023-07-13 00:00

Sample Output :-

START_DATE END_DATE NO_OF_HOURS


2023-07-01 00:00:00.000 2023-07-17 00:00:00.000 288
2023-07-12 00:00:00.000 2023-07-13 00:00:00.000 24

*/
GO

create table COUNTWORKINGHOURS(START_DATE datetime,END_DATEdatetime,NO_OF_HOURS


int)

exec SP_COUNTWORKINGHOURS '2023-07-01 00:00','2023-07-17 00:00';


exec SP_COUNTWORKINGHOURS '2023-05-22 00:00','2023-06-04 00:00';
exec SP_COUNTWORKINGHOURS '2023-07-07 00:00','2023-07-08 23:00';
exec SP_COUNTWORKINGHOURS '2023-03-05 00:00','2023-03-26 00:00';
exec SP_COUNTWORKINGHOURS '2023-07-12 00:00','2023-07-13 00:00';

select * from COUNTWORKINGHOURS

Create or Alter Procedure SP_COUNTWORKINGHOURS


@Start_Date datetime,
@End_Date datetime
as
begin
declare @DayName varchar(50);
declare @TotalSunday int = 0, @Total_1_2_Saturday int = 0;
declare @Start_Print datetime , @End_Print datetime;
set @Start_Print = @Start_Date
set @End_Print = @End_Date

while(@Start_Date <= @End_Date)


begin

set @DayName = datename(dw,@Start_Date)


if(@DayName = 'Sunday')
begin
set @TotalSunday = @TotalSunday+1
end
if(@DayName = 'Saturday' and (day(@Start_Date) between 1 and 14))
begin
set @Total_1_2_Saturday = @Total_1_2_Saturday + 1
end

set @Start_Date = dateadd(day,1,@Start_Date)


end
declare @total_sat_sun int = @TotalSunday + @Total_1_2_Saturday;
declare @total_days int = datediff(DAY,@Start_Print,@End_Print) ;
declare @start_Sat_Sun int = 0, @end_Sat_Sun int = 0
if(datename(dw,@Start_Print) = 'Saturday' or datename(dw,@Start_Print) =
'Sunday')
begin
set @start_Sat_Sun = @start_Sat_Sun + 1
end
if(datename(dw,@End_Print) = 'Saturday' or datename(dw,@End_Print) =
'Sunday')
begin
set @end_Sat_Sun = @end_Sat_Sun + 1
end

declare @No_of_Hours as bigint;

declare @start_hours int, @end_hours int


set @start_hours = DATEDIFF(HOUR,cast(@Start_Print as date),@Start_Print)
set @end_hours = DATEDIFF(HOUR,cast(@End_Print as date),@End_Print)

set @No_of_Hours = ((@total_days - @total_sat_sun + @start_Sat_Sun +


@end_Sat_Sun) *24 ) + @end_hours -@start_hours
insert into COUNTWORKINGHOURS values(@Start_Print,@End_Print,@No_of_Hours)
end

select * from COUNTWORKINGHOURS

truncate table COUNTWORKINGHOURS

select cast(DATEADD(day,1,'2023-07-08 23:00') as date)

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DML_Q1] Script Date:


09-08-2023 13:00:16 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DML_Q1]


AS
/*Use the tables Product_details,Sales.
Q.3. Create a view to display columns
User_id,Colour,Total_Amount,Total_Points_Earned.
Buying each product of specific colors generate specific points and each color has
different purchasing points.
For Black product – you get 5 points, for Yellow - 2 points, Silver-10 points and
Others - 0 point.

Calculate Total_points_Earned by each user.Total_points_Earned can be calculated


by dividing those points from total_amount

Display a column called Most_purchased_product which will show the most purchased
Product overall.
Also display a column called Total_Purchase_Count to show how many times the
most_purchased_product is purchased by each Users.
If any of the values of Total_amount, Total_Points_Earned or Total_Purchase_Count
is Null then replace it with 0.

Create a Non-Clustered index on Product_details table.

(Tag: Views,Joins)

Please keep object name as follows:


View-> Vw_DML_Q3

Output Sample
USER_ID Total_amount Total_Points_Earned Color
Total_Purchase_Count Most_purchased_product
17044 2294.99 458.998 Black 0
870
1229 4454.10 0.00 Blue 4
870
1419 1187.78 593.89 Yellow 4
870
*/
GO

create or alter view Vw_DML_Q3


as
select
D.User_id,D.Total_amount,C.Color,C.Total_Purchase_Count,C.Most_purchased_product
from
(
select s.User_id,p.ProductID, sum(p.Listprice * s.OrderQty) Total_amount
from product_details p
join Sales_2 s on p.ProductID = s.ProductID
group by s.User_id,p.ProductID)D
join
(
select A.User_id,A.Color,B.Total_Purchase_Count,B.Most_purchased_product from (
select s.User_id,p.Color , ROW_NUMBER() over(partition by s.User_id order by
count(p.color) desc) as RN
from product_details p
join Sales_2 s on p.ProductID = s.ProductID
group by s.User_id,p.Color
) A
join
(
select s.User_id, count(*) Total_Purchase_Count, p.ProductID Most_purchased_product
from product_details p
join Sales_2 s on p.ProductID = s.ProductID
where p.ProductID = (
select top 1 p.ProductID
from product_details p
join Sales_2 s on p.ProductID = s.ProductID
group by p.ProductID
order by count(*) desc
)
group by s.User_id, p.ProductID
) B on a.User_id = B.User_id
where RN = 1
) C on c.User_id = D.User_id

select * from Vw_DML_Q3

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DQL_Q1] Script Date:


09-08-2023 14:52:38 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DQL_Q1]


AS
/*
Refer the table Mat_cost which maintains the details of the cost of materials.
We need to calculate a new cost in a column INWARDS which will be the calculated
as
the total of stock rs per litre and volume in litre, and deduct from it the stock
rs per litre of the previous month
grouped by each product.
For the values appearing as N ull, should be replaced by 0.
Also, if there is no previous month, the value of that month should be displayed
as 0.

Create a view to generate a matrix to show the total inwards calculated per month
of the products having product code 1,4,6.
Also, display the grand total of the inwards per month and the grand total for
each product.

Please keep the object names as follows:


View Name - VW_Mat_cost
Column names of the view should be exactly same as shown below.

The Output should be in the below format:


One Sample record is also displayed below.

PROD_CODE|January|February| March| April| May| June| July|


August| September| October| November| December| GRAND_TOTAL
1 0 8419.98 21407.48 34844.56 14985.1 16069.9
27411.58 17421.8 13638.84 14569.42 15710.3 21608.48 206087.44
4 <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
<VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
6 <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
<VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
GRAND_TOTAL <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
<VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE> <VALUE>
(Tag: Views, Subqueries, Cube, Pivot, Windows functions)

*/
GO

create or alter view vw_mat_cost


as
select
case
when grouping(prod_code)=1 then 'grand_total'
else
cast(prod_code as varchar)
end
as prod_code
,sum(january) as january
,sum(february) as february
,sum(march) as march
,sum(april) as april
,sum(may) as may
,sum(june) as june
,sum(july) as july
,sum(august) as august
,sum(september) as september
,sum(october) as october
,sum(november) as november
,sum(december) as december
,sum(grand_total) as grand_total
from (
select
prod_code,january,february, march, april, may, june,july, august, september,
october, november, december,
sum(january + february + march + april + may + june + july + august + september +
october + november + december) as grand_total
from
(
select
prod_code,
[1] as january, [2] as february, [3] as march,
[4] as april, [5] as may, [6] as june,
[7] as july, [8] as august, [9] as september,
[10] as october, [11] as november, [12] as december from (
select prod_code,monthofyear,year,isnull((volinltr + stkrsperltr) -
lag(stkrsperltr) over(order by prod_code),0) as inwards
from mat_cost where prod_code in( 1 , 4, 6)) a
pivot (
sum(inwards)
for monthofyear in ([1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11],
[12], [13])
) as pivottable
)b
group by
prod_code,january,february, march, april, may, june,july, august, september,
october, november, december

) v
group by rollup(prod_code)
select * from vw_mat_cost

***********************************************************************************
*************************************************************
USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DQL_Q2] Script Date:


09-08-2023 16:03:32 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DQL_Q2]


AS
/*Q.1. Refer the tables Employee and Department. Emps hired on or before 15th of
any month are paid on
the last Friday of that month. Those hired after 15th are paid on the first Friday
of the following month.
Create a view to display all details of emplo yees with their hire date and their
first pay date.

Display one column called NEW_NAME which will show first 50% part of the name in
lower case and
remaining part of the name in upper case.
Display one more column called EMP_JOB showing first name of employee with his/her
job (job in bracket).
E.g., David (Shopkeeper).
Display another column called EMP_POSITION. An employee who has atleast 2
reportees reporting to him,
mark his postion as SUPER SENIOR whereas mark others as SENIOR

(Tag: Views, String functions, Date functions, Union, Joins)

Please keep object name as follows:


View Name --> VW_EMP_DETAILS

Sample Output :-
(Please keep same column names as below)

empid name salary hiredate paydate deptid


New_Name Emp_job Emp_Position
1001 Rahul P Roy 55000 2020-01-21 2020-02-07 D001 rahul P ROY
Rahul (Accounting) Senior
1004 Riya Sharma 45500 2021-03-13 2021-03-26 D003 riya SHARMA
Riya (IT) Super Senior
1009 Jeena 12000 2018-11-17 2018-12-07 D004 jeENA
Jeena(Sales) Senior
*/
GO

CREATE OR ALTER VIEW VW_EMP_DETAILS AS


SELECT
e.empid,
e.name,
e.salary,
e.hiredate,
CASE
WHEN DAY(e.hiredate) <= 15 THEN MAX(DATEADD(DAY,CASE WHEN DATEPART(WEEKDAY,
eomonth(e.hiredate)) = 7 THEN -1
WHEN DATEPART(WEEKDAY,
eomonth(e.hiredate)) = 1 THEN -2
ELSE -((DATEPART(WEEKDAY,
eomonth(e.hiredate)) + 1) % 7)
END, eomonth(e.hiredate)))

ELSE DATEADD(DAY,(CASE WHEN DATEPART(WEEKDAY, dateadd(day,1,eomonth(e.hiredate)))


<= 5 THEN 6 -
DATEPART(WEEKDAY, dateadd(day,1,eomonth(e.hiredate))) ELSE 13 -
DATEPART(WEEKDAY, dateadd(day,1,eomonth(e.hiredate)))
END),dateadd(day,1,eomonth(e.hiredate)))
END AS paydate,

e.deptid,

LOWER(CASE WHEN CHARINDEX(' ', e.name) > 0 THEN LEFT(e.name, CHARINDEX(' ', e.name)
- 1) ELSE e.name END) + ' ' + UPPER(CASE
WHEN CHARINDEX(' ', e.name) > 0 THEN SUBSTRING(e.name, CHARINDEX(' ', e.name) + 1,
LEN(e.name) - CHARINDEX(' ', e.name))
ELSE ''
END) AS New_Name,
CASE
WHEN CHARINDEX(' ', e.name) > 0 THEN LEFT(e.name, CHARINDEX(' ', e.name))
ELSE e.name
END + ' (' + d.deptname + ')' AS Emp_job,
CASE
WHEN (
SELECT COUNT(*)
FROM Employee
WHERE manager = e.empid
) >= 2 THEN
'Super Senior'
ELSE
'Senior'
END AS Emp_Position
FROM
Employee e
JOIN Department d ON e.deptid = d.deptid
group by e.empid,
e.name,
e.salary,
e.hiredate,
e.deptid,
d.deptname

select * from VW_EMP_DETAILS

***********************************************************************************
*************************************************************
USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DQL_Q3] Script Date:


09-08-2023 16:35:10 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DQL_Q3]


AS
/*Q.1. 4.Refer table EVENTSDATA. A Worker has given multiple works to do.
Start and End time of every work is recorded after every 10 minutes interval.
Create a view to calculate the number of minutes and its start and end time that
the worker took to complete each work.
Sample output is shown below. Use Recursive CTE to implement the same.

(Tag: Recursive CTE)

Please keep object name as follows:


View Name --> Vw_Worker_Event

Sample Output :-
(Please keep same column names as below)

Start_Time End_Time Minutes


10:00:00.0000000 10:30:00.0000000 30
10:40:00.0000000 11:00:00.0000000 20
11:10:00.0000000 11:20:00.0000000 10

*/
GO
create or alter view Vw_Worker_Event
as
with cte1 as (
select eventtime,status,row_number() over (order by eventtime) as rn
from eventsdata
)
, cte2 as (
select c1.eventtime as start_time, min(c2.eventtime) as end_time,
datediff(minute, c1.eventtime, min(c2.eventtime)) as minutes
from cte1 c1
join cte1 c2 on c1.rn < c2.rn and c2.status = 'ended'
where c1.status = 'started'
group by c1.eventtime
)
select start_time, end_time, minutes
from cte2;

select * from Vw_Worker_Event

***********************************************************************************
*************************************************************

USE [Parikshak]
GO

/****** Object: StoredProcedure [schema_HRM2457].[SP_prob2_DQL_Q4] Script Date:


09-08-2023 16:57:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE procedure [schema_HRM2457].[SP_prob2_DQL_Q4]


AS
/*
Create a stored procedure named sp_prob2_scd_2 to load data from source to target
table using SCD Type 2 method.
Data from all source tables should be loaded to their respective target tables as
mentioned in the lookup table named TBLLOOKUP.
Use Dynamic SQL to implement the same.
Create the target tables (shown in Sample Output below) that maintains all the
historical,
changed and new data if any in the source data.
Maintain a Active flag column (Y/N) named ACTIVE in all the target tables to show
if its current or historical data.
Create a trigger on emp_src table and create a table named EMP_LOGTBL (schema same
as emp_src table) to log all the data that are newly inserted into emp_src table.
Trigger should be invoked whenever a new record is inserted into the emp_src table.
Once Stored proc and trigger is created,Execute the SP once and full load data
from source to target.
Once that is done, Insert and Update the below records manually in the mentioned
source tables:
(Refer the source tables in TBLLOOKUP table for the data and schema.)

INSERT below records into source tables:::

Table Name eid ename esal edept


emp_src E206 Rebecca 48000 10
emp_src E207 Mark 62000 10

Table Name Cust_ID cust_name loc membership


Customer_src 30016 Danish Delhi Yes
Customer_src 30017 Akhil Mumbai No

Update below records in source tables:::

Table Name eid ename esal edept


emp_src E202 Preeta 52000 20
emp_src E205 Danny 71000 30

Table Name Cust_ID cust_name loc membership


Customer_src 30014 Celina Bangalore Yes
Customer_src 30012 Thomas Chennai Yes

Above records should be automatically inserted/updated in the target tables in SCD


type 2
method after running the stored procedure.

Output::::
Sample Target records in Target tables:

Emp_trg table:
eid ename esal edept Active
E202 Preeta 35000 20 N
E202 Preeta 52000 20 Y
E206 Rebecca 48000 10 Y

Customer_trg table:
Cust_ID cust_name loc membership Active
30014 Celina Mumbai Yes N
30014 Celina Bangalore Yes Y

Please keep object names and column names exactly same as mentioned in the
question.

(Tags: Dynamic SQL, Temp tables, Triggers , SCD type2)


*/
GO

select * from emp_src


select * from CUSTOMER_SRC
select * from TBLLOOKUP

INSERT INTO emp_data (eid, ename, esal, edept) VALUES ('E206', 'Rebecca', 48000,
10)
INSERT INTO emp_data (eid, ename, esal, edept) VALUES ('E207', 'Mark', 62000, 10)

INSERT INTO Customer_src (Cust_ID, cust_name, loc, membership) VALUES (30016,


'Danish', 'Delhi', 'Yes')
INSERT INTO Customer_src (Cust_ID, cust_name, loc, membership) VALUES (30017,
'Akhil', 'Mumbai', 'no')

CREATE or alter PROCEDURE sp_prob2_scd_2


AS
BEGIN
declare @count int = (select count(*) from TBLLOOKUP), @start int = 0
while(@start < @count)
begin
declare @source_table_name varchar(30), @target_table_name varchar(30),
@matching_key varchar(30), @target_columns varchar(max),
@source_columns varchar(max)

set @source_table_name = (select sourcetable from TBLLOOKUP order by sourcetable


offset @start rows fetch next 1 row only)
set @target_table_name = (select targettable from TBLLOOKUP order by sourcetable
offset @start rows fetch next 1 row only)
set @matching_key = (select SourceMatchingKey from TBLLOOKUP order by sourcetable
offset @start rows fetch next 1 row only)
set @target_columns = (select
concat(SourceMatchingKey,',',trg_col1,',',trg_col2,',',trg_col3,',','Active') from
TBLLOOKUP order by sourcetable offset @start rows fetch next 1 row only)
set @source_columns = (select
concat('Source.',SourceMatchingKey,',Source.',src_col1,',Source.',src_col2,',Source
.',src_col3,',','''Y''') from TBLLOOKUP order by sourcetable offset @start rows
fetch next 1 row only)

DECLARE @sql NVARCHAR(MAX)


SET @sql = N'
MERGE INTO '+@target_table_name+' AS target
USING '+@source_table_name+' AS source
ON (target.'+@matching_key+' = source.'+@matching_key+')
WHEN MATCHED THEN
UPDATE SET target.Active = ''N''
WHEN NOT MATCHED THEN
INSERT ('+@target_columns+')
VALUES ('+@source_columns+');';

EXEC sp_executesql @sql;

set @start = @start + 1


end
END;

EXEC sp_prob2_scd_2;

CREATE TRIGGER tr_emp_data_insert


ON emp_data
AFTER INSERT
AS
BEGIN
INSERT INTO EMP_LOGTBL (eid, ename, esal, edept)
SELECT i.eid, i.ename, i.esal, i.edept
FROM inserted AS i;
END;

-- Insert records into emp_data


INSERT INTO emp_data (eid, ename, esal, edept)
VALUES
('E202', 'Preeta', 52000, 20),
('E205', 'Danny', 71000, 30);

-- Insert records into Customer_src


INSERT INTO Customer_src (Cust_ID, cust_name, loc, membership)
VALUES
(30014, 'Celina', 'Bangalore', 'Yes'),
(30012, 'Thomas', 'Chennai', 'Yes');

CREATE TABLE EMP_LOGTBL (


eid VARCHAR(10) PRIMARY KEY,
ename VARCHAR(50),
esal INT,
edept INT
);
CREATE or alter TRIGGER tr_emp_data_insert
ON emp_data
AFTER INSERT
AS
BEGIN
INSERT INTO EMP_LOGTBL (eid, ename, esal, edept)
SELECT i.eid, i.ename, i.esal, i.edept
FROM inserted AS i;
END;
select * from emp_trg

***********************************************************************************
*************************************************************

You might also like