Select car of max(date) for every employee [duplicate] - sql

This question already has answers here:
Fetch the rows which have the Max value for a column for each distinct value of another column
(35 answers)
Select First Row of Every Group in sql [duplicate]
(2 answers)
Return row with the max value of one column per group [duplicate]
(3 answers)
GROUP BY with MAX(DATE) [duplicate]
(6 answers)
How to return only latest record on join [duplicate]
(6 answers)
Closed last year.
I would need a code for the following problem:
I have a table like this:
Employee
Year
Month
Car
Tom
2021
9
Ford
Tom
2021
10
Ford
Tom
2021
11
Ford
Tom
2021
12
Renault
Tom
2022
1
Renault
Mark
2021
12
VW
Mark
2022
1
VW
Mark
2022
2
VW
Joe
2021
8
Opel
Joe
2021
9
Tesla
Joe
2021
10
Ferrari
And I would need the car used by the employee for the last possible date. So the result should be:
Employee
Car
Tom
Renault
Mark
VW
Joe
Ferrari
With:
select employee, max(year || month) from table.cars
group by employee
I get the max(date) for every employee, but I do not know how to join the cars to the max(date).
How can I get the result I want?

You can use ROW_NUMBER() analytic function such as
SELECT Employee, Car
FROM (SELECT ROW_NUMBER() OVER
(PARTITION BY Employee ORDER BY year DESC, month DESC) AS rn,
c.*
FROM cars c)
WHERE rn = 1
provided that the data type of the year and month are of string type, then you can replace the part ORDER BY year DESC, month DESC with
ORDER BY TO_NUMBER(TRIM(year)) DESC, TO_NUMBER(TRIM(month)) DESC

with t as
(
select *,
row_number() over (partition by employee order by year desc, month desc) rn
from cars
)
select employee, car
from t
where rn = 1

Try this:
select employee, car
from (
Select *, ROW_NUMBER(partition by employee order by year, month DESC) as row_number
from cars
)a
Where row_number = 1

Related

Order table by the total count but do not lose the order by names

I have a table, consisting of 3 columns (Person, Year and Count), so for each person, there are several rows with different years and counts and the final row with total count. I want to keep the table ordered by Name, but also order it by the total count.
So the rows should be ordered by sum, but also grouped by the Person and ordered by year. When I am trying to order by sum, of course, both person and years are messed up. Is there a way to sort like this?
You've stored those "total" rows as well? Gosh! Why did you do that?
Anyway: if you
compute rank for rows whose year column is equal to 'total' and
add case expression into the order by clause,
you might get what you want:
SQL> with sorter as
2 (select name, cnt,
3 rank() over (order by cnt) rnk
4 from test
5 where year = 'total'
6 )
7 select t.*
8 from test t join sorter s on s.name = t.name
9 order by s.rnk, case when year = 'total' then '9'
10 else year
11 end;
NAME YEAR CNT
---- ----- ----------
John 2018 3
John 2019 2
John total 5
Bob 2017 2
Bob 2019 4
Bob total 6
6 rows selected.
SQL>

How to select "best" (Max) value by day for each category? In MS SQL

I'm using MS SQL and am trying to find the "best" (Max sales volume) day for customer reps. I currently have a table with the columns:
RepName, Date, Volume
That has the following data
- Joe Salesman, 01/01/2021, 2
- Mike Moneymaker, 01/01/2021, 14
- Rachel Revenue, 01/01/2021, 7
- Joe Salesman, 01/02/2021, 9
- Mike Moneymaker, 01/02/2021, 8
- Rachel Revenue, 01/02/2021, 12
- Joe Salesman, 01/03/2021, 7
- Mike Moneymaker, 01/03/2021, 11
- Rachel Revenue, 01/03/2021, 14
with this continuing up to today's data.
I'm trying to list the Max Volume per Rep, and the respective date the rep obtained that volume. This would look like:
- Joe Salesman, 01/02/2021, 9
- Mike Moneymaker, 01/01/2021, 14
- Rachel Revenue, 01/03/2021, 14
Current Code I'm using is more or less in this format:
SELECT RepName, Date, MAX(Volume)
FROM MyTable
GROUP BY RepName, Date
However, this is returning all rows of data in MyTable, instead of showing the maximums.
Anybody have any insight or tips?
Use window functions:
SELECT t.*
FROM (SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY RepName ORDER BY Volume DESC) as seqnum
FROM MyTable t
) t
WHERE seqnum = 1;

SQL distinct query over two tables

I would like to find the distinct reviews (by year) for each employee showing only the most recent review (by year)
Employee List Employee Reviews
Number | Employee Name GUID | Number | Year
1234 John x5848 1234 2016
4526 Jim xd565 1234 2015
1123 Pam cr484 1123 2016
Result Needed:
Number | Name | GUID | Year
1234 John x5848 2016
1123 Pam cr484 2016
I can't figure out how to write a SQL query that would return me the above results. Anyone have any experience with a query like this or similar?
You can rank your records by giving row numbers to them:
select
guid, number, year,
row_number() over (partition by number order by year desc) as rn
from employee_reviews;
This gives the newest records (order by year desc) per employee (partition by number) row number 1. Hence:
select emp.number, emp.name, rev.guid, rev.year
from employee amp
join
(
select
guid, number, year,
row_number() over (partition by number order by year desc) as rn
from employee_reviews
) rev on rev.number = emp.number and rev.rn = 1;

How to get top records of subset?

Say I have a table
StoreID TotalSales Month Year
-- ---------- ----- ----
1 10 1 2012
2 2 1 2012
3 15 1 2012
1 4 2 2012
2 5 2 2012
I need: For each unique "Month/Year", grab the top two StoreID's with the highest Sales.
I'm at a loss on how to do this. I tried with a cross apply but that doesn't seem to work. This is all way over my head so hopefully someone can give me a nudge in the right direction.
This query uses Common Table Expression and Window Function to be able to get all the columns within the row. It works on SQL Server 2005 and up
WITH records
AS
(
SELECT StoreID, TotalSales , Month, Year,
DENSE_RANK() OVER (PARTITION BY Month, Year
ORDER BY TotalSales DESC) rn
FROM tableName
)
SELECT StoreID, TotalSales , Month, Year
FROM records
WHERE rn <= 2
SQLFiddle Demo

Retrieve highest value from sql table

How can retrieve that data:
Name Title Profit
Peter CEO 2
Robert A.D 3
Michael Vice 5
Peter CEO 4
Robert Admin 5
Robert CEO 13
Adrin Promotion 8
Michael Vice 21
Peter CEO 3
Robert Admin 15
to get this:
Peter........4
Robert.......15
Michael......21
Adrin........8
I want to get the highest profit value from each name.
If there are multiple equal names always take the highest value.
select name,max(profit) from table group by name
Since this type of request almost always follows with "now can I include the title?" - here is a query that gets the highest profit for each name but can include all the other columns without grouping or applying arbitrary aggregates to those other columns:
;WITH x AS
(
SELECT Name, Title, Profit, rn = ROW_NUMBER()
OVER (PARTITION BY Name ORDER BY Profit DESC)
FROM dbo.table
)
SELECT Name, Title, Profit
FROM x
WHERE rn = 1;