Max from Query from Select data - sql

I am pretty new to SQL and need some help with a query. I am trying the find the MAX TradeCodeID using the following query. It is not returning the data I need. It is pretty much returning t.
select distinct
t.useremployeeid,
max(t.usertradeID),
t.Projectfullname,
t.userfirstname + ' '+ t.userlastname as GreatestPM
from
(select distinct
users.UserTradeId, UserEmployeeID, UserFirstName, UserLastName,
ProjectFullName, ProjectManager,
max(ScheduleDate) as LastDate
from
schedules
left outer join
users on ScheduleUserID = UserID
left outer join
Phases on SchedulePhaseID = PhaseID
left outer join
Projects on phases.ProjectID = projects.ProjectID
left outer join
UserTrades on UserTrades.UserTradeID = Users.UserTradeID
where
users.useractive = 1
and users.useremployeeid <> 0
and users.usertradeid between 21 and 24
and projectfullname is not null
group by
users.UserTradeid, UserEmployeeID, UserFirstName, UserLastName,
ProjectFullName, ProjectManager
having
max(scheduledate) > getdate() ) t
group by
t.projectfullname, t.userfirstname,t.userlastname, UserEmployeeID
order by
t.projectfullname
From the following data set:
useremployeeid UserTradeID Projectfullname GreatestPM
--------------------------------------------------------------------------------
12121 22 162331.05 John Smith
25487 21 166324.1 Chuck Norris
45639 21 166324.1 Brad Pitt
35789 23 166324.1 John Doe
15697 24 166324.1 Matt Damon
28957 23 166324.1 Taylor Swift
76985 21 166324.1 Tony Romo
25496 21 166324.1 George Strait
85695 22 167091.1 Robin Roberts
75632 21 167091.1 Scott Smith
66897 22 1663341.01 Garth Brooks
58766 21 1663341.01 Travis Tritt
37895 21 1663341.01 Sara Roberts
95687 21 1663352.01 Justin Timberlake
85697 24 1663352.01 Sally Walker
I am looking to get the following results:
useremployeeid UserTradeID Projectfullname GreatestPM
----------------------------------------------------------
12121 22 162331.05 John Smith
15697 24 166324.1 Matt Damon
85695 22 167091.1 Robin Roberts
66897 22 1663341.01 Garth Brooks
85697 24 1663352.01 Sally Walker
Thank you for the help.

Related

Using multiple inner joins and sorting result

In my DB there are three tables. I am trying to figure out how to List the school name, class name and teacher's name. Sort the records by class name within school name. I have a query but it is not working. How can I list the school name, class name and teacher's name and sort record by class name within school name?
SELECT c.class_name FROM class c INNER JOIN teacher t WHERE t.teacher_id = c.teacher_id INNER JOIN school s WHERE t.school_id = s.school_id;
TABLES
SQL> select * from class;
CLASS_ID CLASS_NAME TEACHER_ID MAX_SEATS_AVAILABLE
---------- ------------------- ---------- -------------------
1 Intro to ALGEBRA 11 12
2 Basic CALCULUS 2 10
3 ABC and 123 1 15
4 Sharing 101 8 10
5 Good Talk, Bad Talk 9 20
6 Nap Time 1 21
7 WRITing 101 5 10
8 Finger Painting 9 14
9 Physics 230 2 20
10 Gym 5 25
10 rows selected.
SQL> select * from teacher;
TEACHER_ID FIRST_NAME LAST_NAME T HOME_ROOM_NUM PHONE_NUM START_DAT HO SCHOOL_ID
---------- ---------------- ---------------- - ------------- ---------- --------- -- ----------
1 FRanK JOHNSON k 10C 22-OCT-97 In 11090
2 LISA JONES h 11Bc 317-587-90 19-JAN-15 iN 123134
87
3 Jeff Dafferty C W8CZ 12-DEC-96 OH 11546
4 Frank MARTIN g 12aA 212-098-98 19-JAN-15 IN 11090
76
5 John Smith H 34C 10-OCT-93 In 123134
6 John Smith G 34C 10-OCT-93 in 11090
7 Lisa Jones G 11E 317-587-90 19-JAN-15 IN 123134
87
8 Trevor Horse k x 19-JAN-15 Oh 11090
9 Gregor Ivan K 12A 317-987-09 10-NOV-96 KY 11090
87
10 Gregor Ivan g 12A 317-987-09 10-NOV-96 Ky 11090
87
11 Pat Francis H 1z1a 123-317-09 19-JAN-15 Il 11546
12
12 Brad Smith G 13A 18-NOV-94 IN 11546
12 rows selected.
SQL> select * from school;
SCHOOL_ID SCHOOL_NAME SCHOOL_TYPE
---------- ----------------------------- ------------
11546 Ivy Tech College COLLegE
11090 LAWRENCE Central Grade School GRADE SCHOOL
11111 Lawrence NORTH High School HIGH SCHooL
19283 Howe High SCHOOL High SchooL
123134 Lawrence Central High School HIGH SCHOOL
192 Little Big Horn Grade School GRADE SCHOOL
You can use the join to get what you want. This will give the all schools with the teachers and there classes.
SELECT DISTINCT
sc.SCHOOL_NAME,
teach.FIRST_NAME,
teach.LAST_NAME ,
cs.CLASS_NAME
FROM
school sc JOIN teacher teach
ON sc.SCHOOL_ID = teach.SCHOOL_ID
JOIN class cs ON cs.TEACHER_ID = teach.TEACHER_ID
ORDER BY
sc.SCHOOL_NAME,cs.CLASS_NAME
SELECT t.FIRST_NAME +' '+t.LAST_NAME, s.SCHOOL_NAME, c.class_name
FROM class c
INNER JOIN teacher t
ON t.teacher_id = c.teacher_id
INNER JOIN school s
ON t.school_id = s.school_id
ORDER BY s.SCHOOL_NAME,c.CLASS_NAME

Copy rows of data in SQL Server

Please help me come up with a solution for the situation being explained below:
ID name address age hobby GPA
---------------------------------------------------------
101 James 100 Garfield St 21 reading 3.13
101 James 100 Garfield St 21 writing 2.63
101 James 100 Garfield St 21 running 3.81
109 Tom 19 Lily Ave 19 dating 3.54
109 Tom 20 Lily Ave 19 climbing 2.76
109 Tom 21 Lily Ave 19 watching 3.91
I want to copy the set of rows with the same ID (eg. 101) and assign each set a State abbreviation(s) by running a single sql query. For instance: adding states CA, NJ, and DE to rows with an ID of 101, the result set is expected to look like this:
ID name address age hobby GPA state
-----------------------------------------------------------------------
101 James 100 Garfield St 21 reading 3.13 CA
101 James 100 Garfield St 21 writing 2.63 CA
101 James 100 Garfield St 21 running 3.81 CA
101 James 100 Garfield St 21 reading 3.13 NJ
101 James 100 Garfield St 21 writing 2.63 NJ
101 James 100 Garfield St 21 running 3.81 NJ
101 James 100 Garfield St 21 reading 3.13 DE
101 James 100 Garfield St 21 writing 2.63 DE
101 James 100 Garfield St 21 running 3.81 DE
Please keep in mind that everything else remains the same way as they were before the addition of the state abbreviations. Also assume I have more than three states to add and integrate to the query, say, I have all 50 states. Thank you for your time and effort in advance!
This should produce that result set:
select x.*, y.st
from tbl x
join
(select 'CA' as st union all
select 'NJ' union all
select 'DE') y
where x.id = 101
Create a new table with IDs and States
ID ST
101 CA
101 NJ
101 DE
109 ..
then join that on your table
SELECT t.*, s.st
FROM tbl t
JOIN states s ON t.id = s.id

SQL Select Distinct returning duplicates

I am trying to return the country, golfer name, golfer age, and average drive for the golfers with the highest average drive from each country.
However I am getting a result set with duplicates of the same country. What am I doing wrong? here is my code:
select distinct country, name, age, avgdrive
from pga.golfers S1
inner join
(select max(avgdrive) as MaxDrive
from pga.golfers
group by country) S2
on S1.avgdrive = s2.MaxDrive
order by avgdrive;
These are some of the results I've been getting back, I should only be getting 15 rows, but instead I'm getting 20:
COUN NAME AGE AVGDRIVE
---- ------------------------------ ---------- ----------
Can Mike Weir 35 279.9
T&T Stephen Ames 41 285.8
USA Tim Petrovic 39 285.8
Ger Bernhard Langer 47 289.3
Swe Fredrik Jacobson 30 290
Jpn Ryuji Imada 28 290
Kor K.J. Choi 37 290.4
Eng Greg Owen 33 291.8
Ire Padraig Harrington 33 291.8
USA Scott McCarron 40 291.8
Eng Justin Rose 25 293.1
Ind Arjun Atwal 32 293.7
USA John Rollins 30 293.7
NIr Darren Clarke 37 294
Swe Daniel Chopra 31 297.2
Aus Adam Scott 25 300.6
Fij Vijay Singh 42 300.7
Spn Sergio Garcia 25 301.9
SAf Ernie Els 35 302.9
USA Tiger Woods 29 315.2
You are missing a join condition:
select s1.country, s1.name, s1.age, s1.avgdrive
from pga.golfers S1 inner join
(select country, max(avgdrive) as MaxDrive
from pga.golfers
group by country
) S2
on S1.avgdrive = s2.MaxDrive and s1.country = s2.country
order by s1.avgdrive;
Your problem is that some people in one country have the same average as the best in another country.
DISTINCT eliminated duplicate rows, not values in some fields.
To get a list of countries with ages, names, and max drives, you would need to group the whole select by country.

SQL Server: Merge Data Rows in single table in output

I have a SQL Server table with the following fields and sample data:
ID Name Address Age
23052-PF Peter Timbuktu 25
23052-D1 Jane Paris 22
23052-D2 David London 24
23050-PF Sam Beijing 22
23051-PF Nancy NYC 26
23051-D1 Carson Cali 22
23056-PF Grace LA 28
23056-D1 Smith Boston 23
23056-D2 Mark Adelaide 26
23056-D3 Hose Mexico 25
23056-D4 Mandy Victoria 24
Each ID with -PF is unique in the table.
Each ID with the -Dx is related to the same ID with the -PF.
Each ID with -PF may have 0 or more IDs with -Dx.
The maximum number of -Dx rows for a given -PF is 9.
i.e. an ID 11111-PF can have 11111-D1, 11111-D2, 11111-D3 up to 11111-D9.
Output expected for above sample data:
ID ID (without suffix) PF_Name PF_Address PF_Age D_Name D_Address D_Age
23052-PF 23052 Peter Timbuktu 25 Jane Paris 22
23052-PF 23052 Peter Timbuktu 25 David London 24
23050-PF 23050 Sam Beijing 22 NULL NULL NULL
23051-PF 23051 Nancy NYC 26 Carson Cali 22
23056-PF 23056 Grace LA 28 Smith Boston 23
23056-PF 23056 Grace LA 28 Mark Adelaide 26
23056-PF 23056 Grace LA 28 Hose Mexico 25
23056-PF 23056 Grace LA 28 Mandy Victoria 24
I need to be able to join the -PF and -Dx as above.
If a -PF has 0 Dx rows, then D_Name, D_Address and D_Age columns in the output should return NULL.
If a -PF has one or more Dx rows, then PF_Name, PF_Address and PF_Age should repeat for each row in the output and D_Name, D_Address and D_Age should contain the values from each related Dx row.
Need to use MSSQL.
Query should not use views or create additional tables.
Thanks for all your help!
select
pf.ID,
pf.IDNum,
pf.Name as PF_Name,
pf.Address as PF_Address,
pf.Age as PF_Age,
dx.Name as D_Name,
dx.Address as D_Address,
dx.Age as D_Age
from
(
select
ID, left(ID, 5) as IDNum, Name, Address, Age
from
mytable
where
right(ID, 3) = '-PF'
) pf
left outer join
(
select
ID, left(ID, 5) as IDNum, Name, Address, Age
from
mytable
where
right(ID, 3) != '-PF'
) dx
on pf.IDNum = dx.IDNum
SqlFiddle demo: http://sqlfiddle.com/#!6/dfdbb/1
SELECT t1.ID, LEFT(t1.ID,5) "ID (without Suffix)",
t1.Name "PF_Name", t1.Address "PF_Address", t1.Age "PF_Age",
t2.Name "D_Name", t2.Address "D_Address", t2.Age "D_Age"
FROM PFTable t1
LEFT JOIN PFTable t2 on LEFT(t1.ID,5) = LEFT(t2.ID,5)
WHERE RIGHT(t1.ID,2) = 'PF'

Retrieve top 48 unique records from database based on a sorted Field

I have database table that I am after some SQL for (Which is defeating me so far!)
Imagine there are 192 Athletic Clubs who all take part in 12 Track Meets per season.
So that is 2304 individual performances per season (for example in the 100Metres)
I would like to find the top 48 (unique) individual performances from the table, these 48 athletes are then going to take part in the end of season World Championships.
So imagine the 2 fastest times are both set by "John Smith", but he can only be entered once in the world champs. So i would then look for the next fastest time not set by "John Smith"... so on and so until I have 48 unique athletes..
hope that makes sense.
thanks in advance if anyone can help
PS
I did have a nice screen shot created that would explain it much better. but as a newish user i cannot post images.
I'll try a copy and paste version instead...
ID AthleteName AthleteID Time
1 Josh Lewis 3 11.99
2 Joe Dundee 4 11.31
3 Mark Danes 5 13.44
4 Josh Lewis 3 13.12
5 John Smith 1 11.12
6 John Smith 1 12.18
7 John Smith 1 11.22
8 Adam Bennett 6 11.33
9 Ronny Bower 7 12.88
10 John Smith 1 13.49
11 Adam Bennett 6 12.55
12 Mark Danes 5 12.12
13 Carl Tompkins 2 13.11
14 Joe Dundee 4 11.28
15 Ronny Bower 7 12.14
16 Carl Tompkin 2 11.88
17 Nigel Downs 8 14.14
18 Nigel Downs 8 12.19
Top 4 unique individual performances
1 John Smith 1 11.12
3 Joe Dundee 4 11.28
5 Adam Bennett 6 11.33
6 Carl Tompkins 2 11.88
Basically something like this:
select top 48 *
from (
select athleteId,min(time) as bestTime
from theRaces
where raceId = '123' -- e.g., 123=100 meters
group by athleteId
) x
order by bestTime
try this --
select x.ID, x.AthleteName , x.AthleteID , x.Time
(
select rownum tr_count,v.AthleteID AthleteID, v.AthleteName AthleteName, v.Time Time,v.id id
from
(
select
tr1.AthleteName AthleteName, tr1.Time time,min(tr1.id) id, tr1.AthleteID AthleteID
from theRaces tr1
where time =
(select min(time) from theRaces tr2 where tr2.athleteId = tr1.athleteId)
group by tr1.AthleteName, tr1.AthleteID, tr1.Time
having tr1.Time = ( select min(tr2.time) from theRaces tr2 where tr1.AthleteID =tr2.AthleteID)
order by tr1.time
) v
) x
where x.tr_count < 48