Leave Approval Status in SQL Server - sql-server

I am using SQL Server 2008 R2, I want to display leave application status that can be either apply, approve, reject or cancel.
If all leave approve then status = approve, like other leaves
but if there are mix status e.g some leave approve , some rejected then status = Partial.
I have written the code but I feel it is complicated, can I get it in one, single query?
create table #t
(
employeeID int,
LeaveCode nvarchar(10),
status nvarchar(50)
)
insert into #t
values(1, 'PL', 'Approve'), (1, 'PL', 'Reject'), (1, 'PL', 'Approve')
;with ct1 as
(
select status, count(status) Cnt
from #t
group by status
),
counters as
(
select count(*) as TotalLeave
from #t
)
select top(1)
CASE
WHEN C1.Cnt = C2.TotalLeave
THEN C1.status
ELSE 'Partial'
END [status]
from
ct1 C1
cross join
counters C2
drop table #t

try this,
create table #t
(
employeeID int,
LeaveCode nvarchar(10),
status nvarchar(50)
)
insert into #t values(1,'PL','Approve'),(1,'PL','Reject'),(1,'PL','Approve')
insert into #t values(2,'PL','Approve'),(2,'PL','Approve'),(2,'PL','Approve')
SELECT
employeeID,
CASE WHEN count(DISTINCT status) = 1 THEN MAX(status) ELSE 'Partail' END [status]
FROM #t
GROUP BY employeeID
drop table #t

SELECT
CASE
WHEN COUNT(DISTINCT t.status) > 1 THEN 'Partial'
ELSE MAX(t.status)
END OveralLeaveStatus
FROM #t t

simply group by employee and check for max(status) <> min(status), if it is difference than it means at least one the status is different
select employeeID,
[status] = case when min([status]) <> max([status]) then 'Partial'
else min([status])
end
from #t
group by employeeID

Related

What is the optimal way to get only latest ID's from table in SQL

I'm trying to get only a single row per Appointment Number in a table storing a history of appointments. It works fine with a few rows but then gets slower? Is this the best way to do this kind of check and I'm just missing some indexes or is there a better way?
DECLARE #temptable TABLE
(
id INT PRIMARY KEY NOT NULL
, ApptNumber INT NOT NULL
, ApptDate DATE NOT NULL
, Notes VARCHAR(50) NULL
)
INSERT INTO #temptable VALUES (1,1,'01-DEC-2018','First Appointment')
INSERT INTO #temptable VALUES (2,1,'01-DEC-2018','')
INSERT INTO #temptable VALUES (3,1,'01-DEC-2018','Rescheduled')
INSERT INTO #temptable VALUES (4,2,'02-DEC-2018','Second Appointment')
INSERT INTO #temptable VALUES (5,2,'02-DEC-2018','Cancelled')
INSERT INTO #temptable VALUES (6,3,'03-DEC-2018','Third Appointment')
INSERT INTO #temptable VALUES (7,4,'04-DEC-2018','Fourth Appointment')
SELECT * FROM #temptable
SELECT MAX(id) FROM #temptable GROUP BY ApptNumber
SELECT tt.* FROM #temptable tt
INNER JOIN (SELECT MAX(id) [Id] FROM #temptable GROUP BY ApptNumber) appts ON appts.Id = tt.id
Solution 1:
select * from (
SELECT f1.*, row_number() over(partition by ApptNumber order by id desc ) rang FROM #temptable f1
) tmp where rang=1
Solution 2:
with tmp as (
select ApptNumber, max(ID) MaxID
from #temptable
group by ApptNumber
)
select f1.* from #temptable f1 inner join tmp f2 on f1.ID=f2.MaxID
Solution 3:
select distinct f3.* from #temptable f1
cross apply
(
select top 1 * from #temptable f2
where f1.ApptNumber=f2.ApptNumber
order by f2.ID desc
) f3
Window function
SELECT tt.*
FROM (
SELECT *, row_number() over (partition by ApptNumber order by id desc) as rn
) tt
where tt.rn = 1

How to write a SQL script that deletes duplicate posts

I have a table with these columns:
id (pk, int identity), imei (varchar), name (varchar), lastconnected (datetime)
Some of the entries in this table have the same name and imei, but different id and different lastconnected date.
How can I effectively filter out all entries that have duplicates (with a SQL script), and then delete the one with the latest lastconnected date?
A simple ROW_NUMBER and DELETE should do the trick:
WITH CTE AS
(
SELECT *,
RN = ROW_NUMBER() OVER(PARTITION BY imei, [name] ORDER BY lastconnected DESC)
FROM dbo.YourTable
)
DELETE FROM CTE
WHERE RN = 1;
This is easy and will solve your problem
DECLARE #table TABLE
(
id int,
name varchar(10),
imei varchar(10)
)
insert into #table select 1, 'a','a'
insert into #table select 2, 'b','a'
insert into #table select 3, 'c','a'
insert into #table select 4, 'a','a'
insert into #table select 5, 'c','a'
insert into #table select 6, 'a','a'
insert into #table select 7, 'c','a'
insert into #table select 8, 'a','a'
WHILE (exists (select '' from #table group by name , imei having count(*) > 1))
BEGIN
delete from #table where id in (
select max(id) from #table group by imei , name having count(*) > 1)
End
select * from #table
My first instinct is to use RANK(). This will delete all duplicates, not just the most recent, in cases where things are duplicated multiple times.
delete a
from (
select id, imei, name, lastconnected, RANK() over(partition by imei, name order by lastconnected) as [rank] from #temp
) as a
where a.rank>1
It selects the maximum of the date for each combination of name and iemi and then deletes that particular row.
DELETE FROM yourtablee
WHERE (lastconnecteddate,name,imei) in
(SELECT max(lastconnecteddate), name,imei
FROM yourtable
GROUP BY name,imei)

SQL:How to keep inserting record number in the target table in INSERT INTO statement

I have query like this:
declare #guidd nvarchar(10)
set #guidd = '11233'
create table rrr_temp(value nvarchar(10), value2 int)
create table rrr_tempA(valueA nvarchar(10), guidd nvarchar(10), ranks int)
insert into rrr_temp values('AAA', 200)
insert into rrr_temp values ('BBB', 400)
insert into rrr_temp values ('CCC', 300)
INSERT INTO rrr_tempA(valueA , guidd , ranks )
SELECT RT.value, #guidd , row_number() over (order by (select NULL))
FROM rrr_temp(nolock) RT
INNER JOIN
(SELECT value, min(value2) AS lastLeg
FROM rrr_temp(nolock) RTL
GROUP BY value) GrpRoute
ON RT.value = GrpRoute.value
ORDER BY value2
select * from rrr_tempA
With the above INSERT iNTO statement, i am able to insert only the record number of source table(rrr_temp) for 'ranks' column of Target table by using 'row_number() over (order by (select NULL))'. But, i want the number to be incremented when target table got inserted. i cannot use IDENTITY. Thanks.
Are you asking about something like this?
select #max_rank = max(ranks)
from rrr_tempA
set #max_rank = IsNull(#max_rank, 0)
INSERT INTO rrr_tempA(valueA , guidd , ranks )
SELECT RT.value, #guidd , #max_rank + row_number() over (order by (select NULL))

SQL SERVER 2008 final select command with stored procedure

i guess it is trivial to get it done right .
in the screen-shot below each user(userid) has two results (which is a kind of a duplicate)
how can i fix query to get only one result per user
(each user can have 2 sets of "TimeIn" and "TimeOut" activities)
so if given user does have a second "entrance" but did not leave yet
i need only the first closed entrance/leave + second entrance/still working
here is the Stored Procedure
create table #tmp (tId int, UserId int,
TimeIn1 smalldatetime, [TimeOut1] smalldatetime,
TimeIn2 smalldatetime, [TimeOut2] smalldatetime, tId2 int,
ActiveDate smalldatetime, ReasonID int, Name nvarchar(100), ReasonType nvarchar(100),
TotalMins int)
insert into #tmp (tId, UserId, TimeIn1, TimeOut1, ActiveDate, ReasonID, Name, ReasonType)
SELECT
t1.tId, t1.UserId, t1.TimeIn, t1.[TimeOut], t1.ActiveDate, t1.ReasonID, tblCustomers.name,tblTimeReas.ReasonType
FROM tblTime t1
inner join tblTimeReas on t1.ReasonID = tblTimeReas.ReasonID
inner join tblCustomers on t1.UserId=tblCustomers.custID
where (t1.userid in (select custID from tblCustomers where Classification =35) )
and (DATEPART(DAY,t1.timein)= DATEPART(DAY,GETDATE()))
and (DATEPART(MONTH,t1.timein)= DATEPART(MONTH,GETDATE()))
and (DATEPART(YEAR,t1.timein)= DATEPART(YEAR,GETDATE()))
update #tmp
set tId2 = (select top 1 tId from
tblTime t2 where (userid in (select custID from tblCustomers where Classification =35)) and DATEDIFF(day,t2.timein,#tmp.timein1)=0
and t2.tId>#tmp.tId order by tId asc)
update #tmp
set TimeIn2 = (select TimeIn from tblTime where tId=tId2),
TimeOut2 = (select [TimeOut] from tblTime where tId=tId2)
update #tmp set TotalMins = (
isnull(DATEDIFF(minute,timein1,timeout1),0)+
isnull(DATEDIFF(minute,timein2,timeout2),0)
)
select * from #tmp order by TimeIn1
drop table #tmp
dont know how , i didn't take a course for sql server & databse but this is my final code for
much flexable filtering
create table #tmp (tId int, UserId int,
TimeIn1 smalldatetime, [TimeOut1] smalldatetime,
ActiveDate smalldatetime, ReasonID int, Name nvarchar(100), ReasonType nvarchar(100),
TotalMins int)
insert into #tmp (tId, UserId, TimeIn1, TimeOut1, ActiveDate, ReasonID, Name, ReasonType)
SELECT
t1.tId, t1.UserId, t1.TimeIn, t1.[TimeOut], t1.ActiveDate, t1.ReasonID, tblCustomers.name,tblTimeReas.ReasonType
FROM tblTime t1
inner join tblTimeReas on t1.ReasonID = tblTimeReas.ReasonID
inner join tblCustomers on t1.UserId=tblCustomers.custID
where (t1.userid in (select custID from tblCustomers where Classification Like '%,35%') )
and (DATEPART(DAY,t1.timein)= DATEPART(DAY,GETDATE()))
and (DATEPART(MONTH,t1.timein)= DATEPART(MONTH,GETDATE()))
and (DATEPART(YEAR,t1.timein)= DATEPART(YEAR,GETDATE()))
and TimeOut is null
update #tmp set TotalMins = (
isnull(DATEDIFF(minute,timein1,GETDATE()),0)
)
select *from #tmp order by TimeIn1
drop table #tmp

SQL Server : check if all rows exists in other table

I need to know if all rows from one table exists in other:
declare #Table1 table (id int)
declare #Table2 table (id int)
insert into #Table1(id) values (1)
insert into #Table1(id) values (4)
insert into #Table1(id) values (5)
insert into #Table2(id) values (1)
insert into #Table2(id) values (2)
insert into #Table2(id) values (3)
if exists (select id from #Table1 where id in (select id from #Table2))
select 'yes exists'
else
select 'no, doesn''t exist'
This query returns yes exists but should return no, doesn't exist because only 1 exists in #Table2, values 4 and 5 don't.
What should I change in my query? Thanks!
IF NOT EXISTS (
SELECT ID FROM #Table1
EXCEPT
SELECT ID FROM #Table2
)
SELECT 'yes exists'
ELSE SELECT 'no, doesn''t exist'
You could use EXCEPT to get the set difference of both tables. If any ID's are returned, both tables are not equal:
SELECT ID
FROM #Table1
EXCEPT
SELECT ID
FROM #Table2
EXCEPT returns any distinct values from the left query that are not also found on the right query.
So, to get your "no, doesnt exist":
;WITH diff AS(
SELECT ID
FROM #Table1
EXCEPT
SELECT ID
FROM #Table2
)
SELECT CASE WHEN COUNT(diff.ID) = 0
THEN 'yes exists'
ELSE 'no, doesnt exist'
END AS Result
FROM diff
select case when count(*) > 0 then 'no' else 'yes' end as AllExist
from #Table1 t1
left outer join #Table2 t2 on t1.id = t2.id
where t2.id is null
This would work as long as both id columns are unique (which they should be if they are id's)
DECLARE #totalRows int;
SET #totalRows = SELECT count(*) from Table1;
RETURN (#totalRows == SELECT count(*) from Table1 JOIN Table2 on Table1.id = Table2.id)

Resources