Select Max with groupby - sql

I have the following table.
I need to select SemesterID,AcadamiYear,AcademicSemester of the record with highest Academic year and Academic semester of the year 2015
Expected output is
2013 1 2
I tried the following query but it returns both of the records
select MAX(AcadamiYear) as Year,
MAX(AcadamicSemester) as Semester
,SemesterID
from
tblSemesterRegistration
where [IntakeYear]='2015'
Group by SemesterID

Since you are searching for a single record you might use TOP 1, ordered by your intend
select TOP 1 *
from
tblSemesterRegistration
where [IntakeYear]='2015'
Order by AcadamiYear DESC, AcadamicSemester DESC

This is the query you're looking for:
SELECT SR.*
FROM tblSemesterRegistration SR
INNER JOIN (SELECT MAX(SR2.AcadamiYear) AS [AcadamiYear]
,MAX(SR2.AcadamicSemester) AS [AcadamicSemester]
,IntakeYear
FROM tblSemesterRegistration SR2
GROUP BY SR2.IntageYear) T ON T.AcadamiYear = SR.AcadamiYear
AND T.AcadamicSemester = SR.AcadamicSemester
AND T.IntakeYear = SR.IntakeYear
WHERE SR.IntakeYear = '2015'
Hope this will help you.

If SemesterID is the primary key, grouping on it will always yield all rows (since it is always unique).
I guess you mean to find back that semester id with the parameters set:
select r.*
from tblSemesterRegistration r
join ( select max(AcadamiYear) as Year
, max(AcadamicSemester) as Semester
from tblSemesterRegistration
where [IntakeYear]='2015'
) m
on r.acadamiyear = m.year
and r.acadamicsemester = m.semester

SELECT MAX(AcadamiYear) AS Year,
MAX(AcademicSemester) AS Semester,
MAX(SemesterID) AS SemesterID
FROM tblSemesterRegistration
WHERE [IntakeYear] = '2015'
GROUP BY IntakeYear

Related

Getting value from MAX(Date) Row in SQL Server

I am trying to get the last supplier of an item, by using the MAX function. What I am trying to achieve is showing what the supplier name was for the row with the MAX(Date) for all the stock items (shown below as account links).
The code I am using bring up multiple dates for the same accountlink, and I am struggling to see why. My code is:
SELECT
MAX(TxDate) AS Date,
ST.AccountLink,
V.Account AS Supplier
FROM _bvSTTransactionsFull AS ST
JOIN Vendor V on ST.DrCrAccount = V.DCLink
WHERE Module = 'AP'
AND Id = 'OGrv'
GROUP BY ST.AccountLink, V.Account
ORDER BY AccountLink
But my results look like the below
Try this out
select AccountLink,Supplier,date from(SELECT
ST.AccountLink,
V.Account AS Supplier,
TxDate as [date],
row_number()over(partition by ST.AccountLink order by TxDate desc)rownum
FROM _bvSTTransactionsFull AS ST
JOIN Vendor V on ST.DrCrAccount = V.DCLink
WHERE Module = 'AP'
AND Id = 'OGrv')t
where t.rownum = 1
The group by has been removed and ranking function is used to achieve the output
You need a simple subquery to select the last supplier.
select X.supplier as LastSupplier, X.Date as lastDate, X.AccountLink
from _bvSTTransactionsFull X
where X.Date = (select max(date)
from _bvSTTransactionsFull Y
where Y.AccountLink=X.AccountLink)
The subquery extracts the last date for any accountLink, so you can use it on the outer where condition.

SQL MAx function with multiple columns showing in apex?

image1 image2I am trying to write an sql function to show the year, playername, and ppg of the player with the highest ppg from each year in our database.
We have a Players table with all the stats, and a team table with stats linked to each season as a team total.
What I want to do is get the highest scorer from each season so:
2010: Jake 10ppg
2011: Jake 12 ppg
2012 Carl 13 ppq
Etc.
here is my current query
SELECT Year, PlayerName, MAX(PPG) AS PPG
FROM PLAYERS_T, TEAM_T
GROUP BY Year
ORDER BY PPG;
However this is not working, what do I need to do to make this work?
This should work, but will show duplicated record if same PPG. Dont know what is the use of Team table there
SQL DEMO
WITH PLAYERS_T as (
SELECT 2010 "Year", 'Jake' "PlayerName", 10 ppg
UNION
SELECT 2011 "Year", 'Jake' "PlayerName", 12 ppg
UNION
SELECT 2012 "Year", 'Carl' "PlayerName", 13 ppg
)
SELECT T1."Year", T1."PlayerName", T1.PPG
FROM PLAYERS_T T1
LEFT JOIN PLAYERS_T T2
ON T1."Year" = T2."Year"
AND T1.PPG < T2.PPG
WHERE T2."Year" IS NULL
OUTPUT
Try this one:
SELECT players_T.playername, players_T.ppg, players_T.year
FROM
(SELECT year, MAX(PPG) AS mx
FROM players_T
GROUP BY year) sub
INNER JOIN players_T ON sub.mx = players_T.ppg
WHERE sub.year = players_T.year
ORDER BY players_T.year
In the subquery, this finds the max ppg per year. Then we join with the players table on the ppg to find the player name. The result should be the player name, ppg and year together. Let me know what you find!
Edit: Need to include a WHERE clause for year

Select all unique names based on most recent value in different field

I have an access database with a table called SicknessLog. The fields are ID, StaffName, [Start/Return], DateStamp.
When a member of staff is off work for sickness then a record is added to the table and the value in the [Start/Return] field is 1. When they return to work a new record is added with the same details except the [Start/Return] field is 0.
I am trying to write a query that will return all distinct staff names where the most recent record for that person has a value of 1 (ie, all staff who are still off sick)
Does anyone know if this is possible? Thanks in advance
Here's one way, all staff that has been sick where it does not exist an event after that where that staff is "nonsick":
select distinct x.staffname
from sicknesslog x
where Start/Return = 1
and not exists (
select 1
from sicknesslog y
where x.StaffName = y.StaffName
and y.DateStamp > x.DateStamp
and y.Start/Return = 0
)
You can use group by to achieve this.
select staffname ,max(datestamp) from sicknesslog where start/return = 1 group by staffname
it will return all latest recored for all staff. If ID column is autogenerated PK then you can use it in max function.
select staffname,MAX(datestamp)
from sicknesslog
where [start/return]=1
group by staffname
order by max(datestamp) desc,staffname
This will retrieve latest records who is sick and off to work
This should be close:
select s.StaffName, s.DateStamp, s.[Start/Return]
from SicknessLog s
left join (
select StaffName, max(DateStamp) as MaxDate
from SicknessLog
group by StaffName
) sm on s.StaffName = sm.StaffName and s.DateStamp = sm.MaxDate and s.[Start/Return] = 1

SQL Query GroupBy with date parameter

Suppose I have a table, TeamRatings, that looks something like this
|---Team----|--ValuationDate--|-Rating-|
|--Saints---|---10/15/2012----|---81.1-|
|--Broncos--|---10/15/2012----|---91.1-|
|--Ravens---|---10/16/2012----|--101.1-|
|--Broncos--|---10/22/2012----|---82.1-|
|--Ravens---|---10/22/2012----|---83.1-|
|--Saints---|---10/29/2012----|---84.1-|
|--Broncos--|---10/28/2012----|---85.1-|
|--Ravens---|---10/29/2012----|---86.1-|
Also, it is assumed that a team's rating remains unchanged until they play a new game, (representing a new record). E.g. The Broncos' rating on date 10/21/2012 is assumed to be 102.8
I want a query with a date parameter, that will return one record per team represnting that team's most recent game prior to the date specified. For instance,
If I input 10/23/2012 as my date parameter, the query should return
|---Team---|-ValuationDate---|-Rating-|
|--Saints--|---10/15/2012----|---81.1-|
|--Broncos-|---10/22/2012----|---82.1-|
|--Ravens--|---10/22/2012----|---83.1-|
Any help is greatly appreciated. Thanks!
On MS SQL Server 2005 or greater you can use a cte with ROW_NUMBER function:
WITH x
AS (SELECT team,
valuationdate,
rating,
rn = Row_number()
OVER(
partition BY team
ORDER BY valuationdate DESC)
FROM teamratings
WHERE valuationdate < #DateParam)
SELECT team,
valuationdate,
rating
FROM x
WHERE rn = 1
You can use a more general query like this:
select Team, x.ValuationDate, Rating
from TeamRatings inner join
(
select Team, max(ValuationDate) as ValuationDate
from TeamRatings
where ValuationDate < #dateParameter
group by Team
) x on TeamRatings.Team = x.Team and TeamRatings.ValuationDate = x.ValuationDate

select least row per group in SQL

I am trying to select the min price of each condition category. I did some search and wrote the code below. However, it shows null for the selected fields. Any solution?
SELECT Sales.Sale_ID, Sales.Sale_Price, Sales.Condition
FROM Items
LEFT JOIN Sales ON ( Items.Item_ID = Sales.Item_ID
AND Sales.Expires_DateTime > NOW( )
AND Sales.Sale_Price = (
SELECT MIN( s2.Sale_Price )
FROM Sales s2
WHERE Sales.`Condition` = s2.`Condition` ) )
WHERE Items.ISBN =9780077225957
A little more complicated solution, but one that includes your Sale_ID is below.
SELECT TOP 1 Sale_Price, Sale_ID, Condition
FROM Sales
WHERE Sale_Price IN (SELECT MIN(Sale_Price)
FROM Sales
WHERE
Expires_DateTime > NOW()
AND
Item_ID IN
(SELECT Item_ID FROM Items WHERE ISBN = 9780077225957)
GROUP BY Condition )
The 'TOP 1' is there in case more than 1 sale had the same minimum price and you only wanted one returned.
(internal query taken directly from #Michael Ames answer)
If you don't need Sales.Sale_ID, this solution is simpler:
SELECT MIN(Sale_Price), Condition
FROM Sales
WHERE Expires_DateTime > NOW()
AND Item_ID IN
(SELECT Item_ID FROM Items WHERE ISBN = 9780077225957)
GROUP BY Condition
Good luck!