SELECT rows containing latest values - sql

How do I SELECT the column1 registries that have the column2 with the latest date and is not null?
For example, I need to return just the line five (employee3).

How about this?
SELECT Employee, MAX(Resignation) Resignation
FROM table
WHERE Resignation IS NOT NULL
GROUP BY Employee
Or, if your table has more columns than you've shown,
SELECT a.*
FROM table a
JOIN (
SELECT Employee, MAX(Resignation) Resignation
FROM table
WHERE Resignation IS NOT NULL
GROUP BY Employee
) b ON a.Employee = b.Employee AND a.Resigation = b.Resignation
This is the "find detail rows with extreme values" query pattern.

Updated with a re-interpretation of the question:
I think you mean:
Return the most recent resignation date for all employees who are currently Resigned. Currently resigned is defined as "having all the same employee records with a resignation date populated for that employee". A single employee record with a NULL resignation date means the employee is still employed; regardless of how many times they have resigned!
This can be accomplished with an exists using a correlated subquery.
and a max along with a group by
First we get a list of all the employees who are not resigned.
Then we compare our full set to the set of employees who are not resigned and only keep employees are not in the list of employees not resigned, next we group by employee and get the max resignation.
SELECT Employee, Max(Resignation) Resignation
FROM Table A
WHERE NOT EXISTS (SELECT 1
FROM Table B
WHERE A.Employee = B.Employee
and B.Resignation is null) --Cooelation occurs here Notice how A
GROUP BY Employee
Cooelation occurs on the line WHERE A.Employee = B.Employee as A.EMPLOYEE refers to a table one level removed TABLE A from the table B.
Pretty sure there would be a way to do this with an apply join as well; but I'm not as familiar with that syntax yet.

Related

SQL How to pull in all records that don't contain

This is a bit of a trick question to explain, but I'll try my best.
The essence of the question is that I have a employee salary table and the columns are like so,: Employee ID, Month of Salary, Salary (Currency).
I want to run a select that will show me all of the employees that don't have a record for X month.
I have attached an image to assist in the visualising of this, and here is an example of what UI would want from this data:
Let's say from this small example that I want to see all of the employees that weren't paid on the 1st October 2021. From looking I know that employee 3 was the only one paid and 1 and 2 were not paid. How would I be able to query this on a much larger range of data without knowing which month it could be that they weren't paid?
You need to join your EmployeeSalary table against a list of expected EmployeeID/MonthOfSalary values, and determine the gaps - the instances where there is no matching record in the EmployeeSalary table. A LEFT OUTER JOIN can be used here, whenever there's no matching record / missing record in your EmployeeSalary table, the LEFT OUTER JOIN will give you NULL.
The following query shows how to perform the LEFT OUTER JOIN, however note that I've joined your table on itself to get the list of EmployeeID and MonthOfSalary values. You would be better to join these from other tables, i.e. I assume you have an Employee table with all the IDs in it, which would be more efficient (and more accurate) to use, than building the ID list from the EmployeeSalary table (like I've done).
SELECT EmployeeList.EmployeeID, MonthList.MonthOfSalary
FROM (SELECT DISTINCT MonthOfSalary FROM EmployeeSalary) MonthList
JOIN (SELECT DISTINCT EmployeeID FROM EmployeeSalary) EmployeeList
LEFT OUTER JOIN EmployeeSalary
ON MonthList.MonthOfSalary = EmployeeSalary.MonthOfSalary
AND EmployeeList.EmployeeID = EmployeeSalary.EmployeeID
WHERE EmployeeSalary.EmployeeID IS NULL
You need first to get the latest value, then to calculate the difference and make a filter on it. The filter can be done thanks to having clause.
I propose you the following starting point, that you might need to adapt, at least to cast some formats according to your column types.
with latest_pay as (
-- Filter to get, for each employee, the latest paid month
select Employee_ID, Month, Salary, max(month) as latest_pay_month
from your_table
group by Employee_ID
)
-- Look for employees not paid since more than 'your_treshold' months
select Employee_ID, latest_pay_month, Salary, datediff(latest_pay_month, getdate(), Month) as latest_paid_month_delay
from latest_pay
having datediff(latest_pay_month, getdate(), Month) > your_threshold
Btw, I know it's an example, but avoid using column names such as Month, which would lead to confusions and errors with SQL keywords
This is ideally where you would use a calendar table - having one available is handy for tasks such as this where you need to find missing dates.
You can build one on the fly, I have done so in this example however you would normally have a permanant table to use.
In order to determin which rows are missing you need to generate a list of expected rows, an outer join to your actual data will then reveal the missing rows.
So here we have a CTE that generates a list of dates (based on a date range you can set), followed by another to give a list of all the EmployeeId values.
You expect each employeeId to have a row for each month, so we do a cross join to generate the list of expected results, we then outer join with the actual data and filter to the null rows, these are the employees who have no been paid for that month.
See example DB<>Fiddle
declare #from date='20210101', #to date='20211001';
with dates as (
select DateAdd(month,n,#from) dt from (
select top(100) Row_Number() over(order by (select null))-1 n from master.dbo.spt_values
)v
), e as (select distinct employeeId from t)
select dt, e.EmployeeId
from dates d cross join e
left join t on DatePart(month,d.dt)=DatePart(month,t.PaidDate) and t.EmployeeId=e.EmployeeId
where d.dt<=#to
and t.EmployeeId is null

Effective Date Employee Entered Pay Group

I need to find the effective date when the employee entered the pay group. It either occurred at the hire date, the rehire date, or Transfer date, whichever is latest. I think what I want to do is create a temp table of most recent effective dates where C1.ACTION=('XFR') AND C1.PAYGROUP=A.PAYGROUP, when the associate is not in that table, give me most recent hire date.
A is Top of Stack Employee Dta
B is Top of Stack Personal Data
C is entire employee record
Most Recent Hire Date is
CASE WHEN A.HIRE_DT<=A.REHIRE_DT THEN A.REHIRE_DT
ELSE A.HIRE_DT END MOST_REC_HIREDT
FYI I know this query is really messed up, that's why I'm asking for help.
SELECT DISTINCT
A.EMPLID
A.FIRST_NAME||' '||A.LAST_NAME WORKERNAME,
CASE
WHEN(Select Max(C1.EFFDT) FROM JOB C1
WHERE (C.EMPLID=C1.EMPLID
AND C1.ACTION=('TAF')
AND C1.PAYGROUP=A.PAYGROUP
AND C1.EFFDT>=(CASE WHEN A.HIRE_DT<A.REHIRE_DT THEN =A.REHIRE_DT
ELSE A.HIRE_DT END MR_HIRE_DT)))
WHEN A.EMPLID NOT IN JOB C1
THEN (CASE WHEN A.HIRE_DT<=A.REHIRE_DT
THEN A.REHIRE_DT
ELSE A.HIRE_DT END MR_HIRE_DT2)
ELSE 'Null' END EFFDT,
A.PAYGROUP
FROM EMPLOYEES A, PERSONAL_DATA B, JOB C
WHERE
A.EMPLID=B.EMPLID
AND
B.EMPLID=C.EMPLID
AND
A.PAYGROUP=C.PAYGROUP
AND
C.EMPL_STATUS in ('A','L','P','S')
It really is important to use ANSI join syntax as it aids (a lot) in working through the logic of how the tables relate. Here we only have 2 tables but in the example query there are 4 table aliases in use (A, B, C and C1). Additionally it helps to use table aliases that relate to the table's name such as E for Employee, J for Job.
What you are seeking is "the latest" date from table JOB, and an extremely useful function row_number() can be used for this. It is used in conjunction with an over() clause which contains a partition by (which is a little similar to group by) and an order by. When ordered by date descending then the row number is 1 for the most recent date (per employee due to the partition used). So, if we filter the subquery below by is_latest = 1 we get one row per employee with the latest effective date. Note this also removes the need to use select distinct now.
SELECT
E.EMPLID
, (E.FIRST_NAME || ' ' || E.LAST_NAME) WORKERNAME
, J.EFFDT PAYGROUP_EFFDT
, E.PAYGROUP
FROM EMPLOYEES E
INNER JOIN (
SELECT
JOB.*
, ROW_NUMBER() OVER (PARTITION BY EMPLID
ORDER BY EFFDT DESC) AS is_latest
FROM JOB
WHERE EMPL_STATUS IN ('A','L','P','S')
) J ON E.EMPLID=J.EMPLID AND J.is_latest = 1
I may be over-simplifying the task here, as I don't fully understand how we get to the dates in question. But well, what I am doing is:
get the greater of the two hire_dt and rehire_dt from the employee record
get the job dates for the employee
from these intermediate results get the first date per employee
The query:
select emplid, max(dt)
from
(
select emplid, greatest(nvl(hire_dt,rehire_dt),nvl(rehire_dt,hire_dt)) as dt from employees
union all
select emplid, effdt as dt from job where action = 'TAF' and empl_status in ('A','L','P','S')
)
group by emplid
order by emplid;

Count transactions within a month only once

I have a situations like below:
I have two database tables. The first table, which I will call TB1 contains all the salaries that the client credits & also the date when the transaction is made.
The second table, which I will call TB2, contains all the products the client has in the bank.
My purpose is to find the number of salaries the client has got before the date he/she got a product (OVERDRAFT in my case) in our bank.
Till now, everything works fine and I have made the query to extract the necessary data.
The only problem, is that I need to improve the query. So, if a certain client has got more than 1 salary (for example every 15 days) within the same month of the same year, the salary is counted only once.
How can I do that PLEASE?
The query is like below:
SELECT TB1.customer_id, COUNT(TB1.customer_id)
FROM table_1 TB1
JOIN
( SELECT TB2.CUSTOMER_ID, TB2.OD_START_DATE
FROM table_2 TB2
JOIN table_2 TB2_MAX
ON TB2.CUSTOMER_ID = TB2_MAX.CUSTOMER_ID
HAVING TB2.od_start_date = MAX(TB2.od_start_date)
GROUP BY TB2.customer_id, TB2.od_start_date
) TB2
ON TB1.CUSTOMER_ID = TB2.CUSTOMER_ID
WHERE TB1.DATE_FROM < TB2.OD_START_DATE
GROUP BY TB1.CUSTOMER_ID
PS: DATE_FROM field contains the date when the transaction is made, while OD_START_DATE field contains the date when the LATEST product is opened.
JOIN in your inner query is redundant. You simply need a MAX date for each customer.
In your outer query you should be counting the DATE_FROM, and not Customer_Id. Since you want to count only once for transactions in a month, Convert DATE_FROM to year month combination and use DISTINCT to count only once.
SELECT TB1.customer_id, COUNT(DISTINCT TO_CHAR(TB1.DATE_FROM,'YYYYMM'))
FROM table_1 TB1
JOIN
( SELECT CUSTOMER_ID, MAX(OD_START_DATE) AS OD_START_DATE
FROM table_2
GROUP BY customer_id
) TB2
ON TB1.CUSTOMER_ID = TB2.CUSTOMER_ID
WHERE TB1.DATE_FROM < TB2.OD_START_DATE
GROUP BY TB1.CUSTOMER_ID

help with query in DB2

i would like your help with my query.I have a table employee.details with the following columns:
branch_name, firstname,lastname, age_float.
I want this query to list all the distinct values of the age_float
attribute, one in each row of the result table, and beside each in the second field show the
number of people in the details table who had ages less than or equal to that value.
Any ideas? Thank you!
You can use OLAP functions:
SELECT DISTINCT age_float,
COUNT(lastname) OVER(ORDER BY age_float) AS number
FROM employee_details
COUNT(lastname) OVER(ORDER BY age_float) AS number orders rows by age, and returns employees count whose age <= current row age
or a simple join:
SELECT A.age_float, count(lastname)
FROM (SELECT DISTINCT age_float FROM employee_details) A
JOIN employee_details AS ED ON ED.age_float <= A.age_float
GROUP BY A.age_float

How to delete duplicate values for a field in a table with a single query?

I want to delete from a table the entries where it has multiple values for Date field.
So say I have Employee table - Id,Name,Date,Points
I want to delete the entries with same Date field which should be unique...just to cleanup
I need to just keep a single entry for date and delete the rest...maybe keep the recent one if possible....
Can anyone please suggest a update query to do this?
Use:
DELETE FROM EMPLOYEE
WHERE id NOT IN (SELECT MAX(e.id)
FROM EMPLOYEE e
WHERE e.date = date
GROUP BY e.date)
The GROUP BY isn't likely to be necessary due to the WHERE clause & only returning one column with an aggregate function on it, but it's included to be safe. This is assuming that when the OP says date field, being SQL Server 2008 that means the DATE data type, not DATETIME.
this query looks at records with same Id,Name and Points and deletes all but the latest
with cte as(
select id,Name, Date, Points,row_number() over(
partition by id,name,points order by date desc) as ind
from emp)
delete from cte where ind>1
If your table has primary key, you can join the table to itself by the dup condition and filter out greater PKs, something like the following:
delete e2
from Employee e
join Employee e2 on e.Date=e2.Date
where e.ID < e2.ID
you can use
DELETE
From Employee
WHERE ID not in (select max(ID) from Employee group by Name)
if the last entry is the recent date, Or you can use this code
DELETE
From Employee
WHERE ID not in
(select max(ID) from Employee e1
where Date=(select max(Date) From Employee where Name=e1.Name)
group by Name)