Which row has the highest value? - sql

I have a table of election results for multiple nominees and polls. I need to determine which nominee had the most votes for each poll.
Here's a sample of the data in the table:
PollID NomineeID Votes
1 1 108
1 2 145
1 3 4
2 1 10
2 2 41
2 3 0
I'd appreciate any suggestions or help anyone can offer me.

This will match the highest, and will also bring back ties.
select sd.*
from sampleData sd
inner join (
select PollID, max(votes) as MaxVotes
from sampleData
group by PollID
) x on
sd.PollID = x.PollID and
sd.Votes = x.MaxVotes

SELECT
t.NomineeID,
t.PollID
FROM
( SELECT
NomineeID,
PollID,
RANK() OVER (PARTITION BY i.PollID ORDER BY i.Votes DESC) AS Rank
FROM SampleData i) t
WHERE
t.Rank = 1

SELECT PollID, NomineeID, Votes
FROM
table AS ABB2
JOIN
(SELECT PollID, MAX(Votes) AS most_votes
FROM table) AS ABB1 ON ABB1.PollID = ABB2.PollID AND ABB1.most_votes = ABB2.Votes
Please note, if you have 2 nominees with the same number of most votes for the same poll, they'll both be pulled using this query

select Pollid, Nomineeid, Votes from Poll_table
where Votes in (
select max(Votes) from Poll_table
group by Pollid
);

Related

Lastest Group Document belongs to

I have two tables, doc_group and group (also document-table, but that is irrelevant here) and I want to get the latest Group for each Doc ID, based on Created date of the group.
DocID
GroupID
1
1
1
2
2
1
2
3
GroupID
Name
Created
1
Group 1
1.1.2022
2
Group 2
10.10.2022
3
Group 3
2.2.2022
I have tried different approaches, but I cannot get it return the just a single line per DocID.
Here is my latest approach:
SELECT
doc_group.DocID
,doc_group.GroupID
, groups.Created
FROM
doc_group
JOIN
groups
ON groups.ID = (
SELECT
TOP 1 ID
FROM
groups
WHERE
groups.ID = doc_group.GroupID
ORDER BY Created DESC
)
Join and use the row_number function as the following:
SELECT DocID, GroupID, Created
FROM
(
SELECT dg.DocID ,dg.GroupID , g.Created,
ROW_NUMBER() OVER (PARTITION BY dg.DocID ORDER BY g.Created DESC) rn
FROM doc_group dg JOIN groups g
ON dg.GroupID = g.GroupID
) T
WHERE rn = 1
ORDER BY DocID
See demo

How to get distinct record from two tables in sql?

i have two table showin below
news (table name)
NewsId NewsDate
1 25-03-2014
2 29-03-2014
newsImageGal (table name)
newsSr newsId newsImages
1 1 images/i.jpg
2 1 images/j.jpg
3 1 images/k.jpg
4 2 images/l.jpg
5 2 images/m.jpg
6 2 images/n.jpg
i want a result like
NewsId NewsDate newsId newsImages
1 25-03-2014 1 images/i.jpg
2 9-03-2014 2 images/l.jpg
i have tried using join query and group by function but it shows duplicate multiple records how to solve this query?
You can write as
;WITH CTE AS
( SELECT N.NewsId
,N.NewsDate
,NIG.newsImages
,ROW_NUMBER() OVER (PARTITION BY N.NewsId ORDER BY NIG.newsSr ASC)
AS rownum
FROM news N
JOIN newsImageGal NIG ON N.NewsId = NIG.newsId
)
SELECT NewsId,
NewsDate,
newsImages
FROM CTE
WHERE rownum = 1
Try this.
SELECT a.NewsId,
a.NewsDate,
b.newsImages
FROM news a
JOIN (SELECT Row_number()OVER(partition BY newsid ORDER BY newssr) rn,
*
FROM newsImageGal) b
ON a.NewsId = b.newsId
WHERE rn = 1
Key here is to find the first image that got added into newsImageGal table per newsid.
so use the window function to create Row_number per newsid in order of newsSr.
SELECT Row_number()OVER(partition BY newsid ORDER BY newssr) rn,
*
FROM newsImageGal
From the above query you can see the rn=1 is the first image that got added into the newsImageGal join the result with news table and filter the result with rn=1
can you try this
select distinct ng.newsId, ng.newsImages
from (
select MIN(newsSr),newsId,newsImages
from newsImageGal
group by newsId,newsImages) ng
join news ne
on ne.newsId=ng.newsId
select n.NewsId,n.NewsDate,g.newsImages
from news n
join newsImageGal g on n.NewsId=g.newsSr
SELECT n.NewsId,
n.NewsDate,
ng.newsId,
ng.newsimages
FROM news n,
(SELECT *,
Rank()OVER(PARTITION BY newsId ORDER BY newsSr DESC) AS rank
FROM newsImageGal) ng
WHERE n.NewsId = ng.newsId
AND rank = 1

SELECT a single field by ordered value

Consider the following two tables:
student_id score date
-------------------------
1 10 05-01-2013
2 100 05-15-2013
2 60 05-01-2012
2 95 05-14-2013
3 15 05-01-2011
3 40 05-01-2012
class_id student_id
----------------------------
1 1
1 2
2 3
I want to get unique class_ids where the score is above a certain threshold for at least one student, ordered by the latest score.
So for instance, if I wanted to get a list of classes where the score was > 80, i would get class_id 1 as a result, since student 2's latest score was above > 80.
How would I go about this in t-sql?
Are you asking for this?
SELECT DISTINCT
t2.[class_ID]
FROM
t1
JOIN t2
ON t2.[student_id] = t1.[student_id]
WHERE
t1.[score] > 80
Edit based on your date requirement, then you could use row_number() to get the result:
select c.class_id
from class_student c
inner join
(
select student_id,
score,
date,
row_number() over(partition by student_id order by date desc) rn
from student_score
) s
on c.student_id = s.student_id
where s.rn = 1
and s.score >80;
See SQL Fiddle with Demo
Or you can use a WHERE EXISTS:
select c.class_id
from class_student c
where exists (select 1
from student_score s
where c.student_id = s.student_id
and s.score > 80
and s.[date] = (select max(date)
from student_score s1
where s.student_id = s1.student_id));
See SQL Fiddle with Demo
select distinct(class_id) from table2 where student_id in
(select distinct(student_id) from table1 where score > thresholdScore)
This should do the trick:
SELECT DISTINCT
CS.Class_ID
FROM
dbo.ClassStudent CS
CROSS APPLY (
SELECT TOP 1 *
FROM dbo.StudentScore S
WHERE CS.Student_ID = S.Student_ID
ORDER BY S.Date DESC
) L
WHERE
L.Score > 80
;
And here's another way:
WITH LastScore AS (
SELECT TOP 1 WITH TIES
FROM dbo.StudentScore
ORDER BY Row_Number() OVER (PARTITION BY Student_ID ORDER BY Date DESC)
)
SELECT DISTINCT
CS.Class_ID
FROM
dbo.ClassStudent CS
WHERE
EXISTS (
SELECT *
FROM LastScore L
WHERE
CS.Student_ID = L.Student_ID
AND L.Score > 80
)
;
Depending on the data and the indexes, these two queries could have very different performance characteristics. It is worth trying several to see if one stands out as superior to the others.
It seems like there could be some version of the query where the engine would stop looking as soon as it finds just one student with the requisite score, but I am not sure at this moment how to accomplish that.

grouping and aggregates with subqueries

I have a query that is designed to find the number of people who went to a hospital more than once. What I have works, but is there a way to do it without the subquery?
SELECT count(*) as counts, hospitals.hospitalname
FROM Patient INNER JOIN
hospitals ON Patient.hospitalnpi = hospitals.npi
WHERE (hospitals.hospitalname = 'X')
group by patientid, hospitalname
having count(patient.patientid) >1
order by count(*) desc
This will always return the number of correct rows (30), but not the number 30. If I remove the group by patientid then I get the entire result set returned.
I solved this problem by doing
select COUNT(*),hospitalname
from
(
SELECT count(*) as counts,hospitals.hospitalname
FROM hospitals INNER JOIN
Patient ON hospitals.npi = Patient.hospitalnpi
group by patientid, hospitals.hospitalname
having count(patient.patientid) >1
) t
group by t.hospitalname
order by t.hospitalname desc
I feel that there has to be a more elegant solution than using subqueries all the time. How could this be improved?
sample data from first query
row # revisits
1 2
2 2
3 2
4 2
same data from second, working query
row# hosp. name revisitAggregate
1 x 30
2 y 15
3 z 5
Simple one-to-many relationship between patient and hospitals
It's super hacky, but here you are:
SELECT TOP 1
ROW_NUMBER() OVER (order by patient.patientid) as Count
FROM
Patient
INNER JOIN hospitals
ON Patient.hospitalnpi = hospitals.npi
WHERE
(hospitals.hospitalname = 'X')
GROUP BY
patientid,
hospitalname
HAVING
count(patient.patientid) >1
ORDER BY
Count desc
select distinct hospitalname, count(*) over (partition by hospitalname) from (
SELECT hospitalname, count(*) over (partition by patientid,
hospitals.hospitalname) as counter
FROM hospitals INNER JOIN
Patient ON hospitals.npi = Patient.hospitalnpi
WHERE (hospitals.hospitalname = 'X')
) Z
where counter > 1

How to query for rows that have highest column value among rows that have same value for one of the columns

I have UserScores Table with data like this:
Id userId Score
1 1 10
2 2 5
3 1 5
I would like to have a query or SQL block that can give me the following output
Id userId Score
3 1 5
2 2 5
That is, I would like to pick rows that are unique by 'user id' that belonging to the highest 'id' column value.
Another solution that would work on SQL Server 2000 (same as INNER JOIN above, but slightly faster) is:
SELECT id, userId, Score
FROM UserScores
WHERE id in (SELECT MAX(id)
FROM UserScores
GROUP BY userId
)
ORDER BY userId
Use:
WITH summary AS (
SELECT t.id,
t.userid,
t.score,
ROW_NUMBER() OVER (PARTITION BY t.userid ORDER BY t.id DESC, t.score DESC) AS rank
FROM USERSCORES sc)
SELECT s.id,
s.userid,
s.score
FROM summary s
WHERE s.rank = 1
How about
SELECT MAX(Id), userId, Score
FROM table
GROUP BY UserId
SELECT U2.id, U2.userId, U2.score
FROM UserScores U2
INNER JOIN (
SELECT U1.userId, MAX(U1.Id) MaxId
FROM UserScores U1
GROUP BY U1.userId
) U3
ON U2.id = U3.MaxId and U2.userId = U3.userId
ORDER BY U2.userId