How to write a SQL Query for the following [closed] - sql

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I have 3 tables Teams, Players and TxP
Teams table has the columns TeamName and TeamID(Primary Key)
Players table has the columns PlayerName and PlayerID(Primary Key)
TxP table has the columns PlayerID, TeamID
I would like to write a query to get the result set as PlayerName, TeamName

SELECT Players.PlayerName, Teams.TeamName
FROM Players
LEFT JOIN TxP ON Players.PlayerID = TxP.PlayerID
LEFT JOIN Teams ON TxP.TeamID = Teams.TeamID
ORDER BY Players.PlayerName
That will give you a row for every player and team combination, including a row with empty TeamName if the player does not have a team.
To only show players that have teams just switch to not using left joins.
For example this might give:
Bob Sample United
Bob Some other team
Chris
If you use normal (inner) joins you won't get the Chris result. If a player can have multiple teams but you only want a single result you'll need a GROUP BY and an aggregate function to group up your team names into a single value.

select Teams.TeamName, TxP.PlayerID
from Teams
right outer join TxP on TxP.TeamID = Teams.TeamID

SELECT Players.PlayerName, Teams.TeamName FROM Players, Teams, TxP
WHERE Teams.TeamID = TxP.TeamID AND Players.PlayerID = TxP.PlayerID

SELECT A.PlayerName, B.TeamName FROM Players A, Teams B, TxP C WHERE
A.PlayerID=C.PlayerID AND B.TeamID=C.TeamID
This query only shows players asigned to at least one team and teams with at least one player

Select Player.PlayerName,Team.TeamName from Player,Team,TXP where Team.TeamId=TXP.TeamId and
Player.PlayerId=TXP.PlayerId

Related

Finding total number of points scores by each team, but relying on foreign relations

I am trying to craft a SQL query to solve the following problem. In the Game table, you see that there is away_team_id and home_team_id. Essentially, I want to find the total number of points for the away and home team for the specific game id.
In order to find the total points, you have to find the players from the respective team that participated in that specific game id. From there, you can sum their points, which would give the total number of points scored by that specific team.
However, I've relied on foreign keys to keep my database maintainable, which has made it a little difficult for me to compute these things. Does anyone mind showing me how I can accomplish this?
For example, I can do this to find the sum of only the away team or home team. I'd ideally want both results in one query. In the following example, 1 is the id of game and 2 is the id of the away team. This will give me the sum of points scored by the away team in game id 1. I can write another query and use the id of the home team, so I can accomplish this in two queries. However, how can I do this in one?
SELECT SUM(statistic.total_points)
FROM player, team, statistic
WHERE player.team_id = team.team_id
AND statistic.player_id = player.player_id
AND statistic.game_id = 1
AND team.team_id = 2
Game:
game_id
away_team_id
home_team_id
Statistic:
game_id
player_id
total_points
Team:
team_id
name
Player:
player_id
team_id
Thanks.
I think you can calculate the statistics per team per game and then join to this table --
WITH gamestats AS (
SELECT s.game_id, p.team_id, SUM(p.total_points) as total_points
FROM statistic s
INNER JOIN player p
ON s.player_id = p.player_id
GROUP BY s.game_id, p.team_id
)
SELECT g.game_id, ISNULL(away.total_points, 0), ISNULL(home.total_points, 0)
FROM game g
LEFT JOIN gamestats away
ON g.game_id = away.game_id
AND g.away_team_id = away.team_id
LEFT JOIN gamestats home
ON g.game_id = home.game_id
AND g.home_team_id = home.team_id

SQL Trying to Outer Join Tables but not working

So, I've a Uni assignment and the lecturer has picked this week to be ill and unable to answer questions.
We've been given a baseball database made up of 4 tables to work with. Table structures are as follows:
TABLENAME:(column1, column2...etc) PK = Primary Key, FK = Foreign Key
PLAYER:(num PK, name, dob, team FK, position)
GAME:(num PK, gamedate, hometeam FK, awayteam FK, homescore,
awayscore)
GAMESTAT:(gamenum PK, playernum FK, homeruns, strikeout)
TEAM:(code PK, name, town, ground)
The aim of this particularly question is to obtain the name of the stadium's (ground in team table), the sum of the home runs scored on that ground, the sum of the strikeouts and then the sum of these two values within a specified date range.
My query and issue are below:
SELECT
t.ground AS GROUNDPLAYED,
SUM(gs.homeruns) as TOTALHOMERUNS,
SUM(gs.strikeouts) AS TOTALSTRIKEOUTS,
SUM(gs.homeruns + gs.strikeouts) AS COMBINEDTOTAL
FROM team t
LEFT OUTER JOIN game g ON g.hometeam = t.code
LEFT OUTER JOIN gamestat gs ON g.num = gs.gamenum
WHERE g.gamedate BETWEEN '7-AUG-2014' AND '13-AUG-2014'
GROUP BY t.ground;
My problem lies in the fact that I get the correct values for games played but regardless of using the LEFT OUTER JOIN, I'm not getting all the stadium's to list. I'm convinced it has to do with the fact that I have had to join to the hometeam from the GAME table and it can only pick the home stadiums based on that.
Any help you may be able to offer would be much appreciated.
Move your WHERE clause to the ON clause for the join to gamestat.
By imposing the filter criteria in the WHERE clause, it occurs after the join has been performed, removing the stadiums with no activity. Once this predicate is moved to the appropriate ON clause it will filter the gamestat's before the join instead of after.
You have experienced the good fortune to encounter this important quirk of SQL, that the positioning of predicates affects the result-set, early in your education.

sqlite Joins with MAX

I have 2 tables. One displays a game played (Date,Where, result,opponent etc) and the other one the details of a batting innings (runs scored, etc) Both tables have a primary key that relates the batting back to a specific game.
I am trying to return the OPPONENT column from Games when the MAX (highest) score is recorded in the table BATTING, but currently i am unsure how to do this.
The 2 tables can be found here
http://i.imgur.com/bqiyD3X.png
The example from these tables would be (max score is 101 in RUNSSCORED, so return the linked OPPONENT from GAMEINDEX which is "Ferndale"
Any help would be great. Thanks.
Is this what you are looking for?
select OPPONENT
from GAMES
where GAMESINDEX in
(select GAMESINDEX from BATTING order by RUNSSCORED desc limit 1);
If there isn't a unique max RUNSSCORED value, then the answer might not be deterministic.
If you want multiple winners in that case, you could use
select OPPONENT
from GAMES natural join BATTING
WHERE RUNSSCORED in (select MAX(RUNSSCORED) from BATTING);
SELECT G.OPPONENT, MAX(B.RUNSSCORED)
FROM GAMES AS G
INNER JOIN BATTING AS B
ON G.GAMESINDEX = B.GAMESINDEX

Join a table to bring in another field [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I currently have this query:
select f.chainid,count(f.player_uuid) as Favorites
from deals_player_favorite f
group by f.chainid
order by 2 desc
Which results in:
CHAINID FAVORITES
25 2771
2207 2282
3940 1954
etc...
I have another table called deals_deals, which also includes the CHAINID field. From this table, I want to join a field called VENUE in, so that each CHAIN ID has a Venue description, and the output would look like this
CHAINID VENUE FAVORITES
25 Amazon.com 2771
2207 Walmart 2282
3940 CVS 1954
etc...
How would I properly join the venue field into the query, using CHAIN id as the key that is in both the deals_deals table and deals_player_favorite table.
I tried an inner join which resulted in way too many results.
The deals_deals table has the fields CHAINID and VENUE..
The deals_player_favorite table has the fields CHAINID and PLAYER_UUID, but does not include all of the CHAINIDs that the deals_deals table, only ones that have been accessed by a player_uuid.
SAMPLE DATA:
deals_deals table
VENUE CHAINID
Walmart 235
Aeropostale 1467
Checker's 881
deals_player_favorite table
PLAYER_UUID CHAINID
23rjior23-32fjdf 235
keep in mind that deals_player_favorite only includes specific CHAINIDs that have been clicked on, not ALL chainids....
SELECT F.chainid, V.Venue, COUNT(f.player_uuid) as Favorites
FROM deals_player_favorite F
INNER JOIN Venues V
ON F.chainid = V.chainid
GROUP BY F.chainid, V.Venue
ORDER BY COUNT(f.player_uuid) DESC
If your problem is that you are getting too many records in your count, then you might want to consider using a subquery and then joining the subquery to get the venue:
select f.chainid,
v.venue,
f.Favorites
from
(
select chainid, count(player_uuid) Favorites
from deals_player_favorite
group by chainid
) f
inner join deals_deals v
on f.chainid = v.chainid
See SQL Fiddle with Demo
The subquery will get your total favorites first, then using the chainid you will get the venue

sql - How to select two different counts from different level of join? [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am not sure the title is correct for my problem and I'd better to give an example.
I have three tables: Publication, Journal, Published. Their columns are like followings:
**Publication table**
pub_id, journal_id
**Journal table**
journal_id, article_id
**Published table**
article_id
So if I do
select pub.pub_id, count(j.article_id)
from publication pub
inner join journal j on pub.journal_id=j.journal_id
group by pub.pub_id
I get the total number of articles of a journal which need to be published for each pub_id, right?
If I do
select pub.pub_id, count(p.article_id)
from publication pub
inner join journal j on pub.journal_id=j.journal_id
inner join published p on j.article_id=p.article_id
group by pub.pub_id
I get the total number of published articles of a journal which need to be published for each pub_id, right?
so through the above two queries, I can get the number of articles that need to be published and the number of articles that have been published.
My question is that how to write a single query to get these two numbers at the same time?
I need to show these two number in the same table.
P.S: I am using Microsoft SQL Server
Try
select pub.pub_id, count(p.article_id), count(distinct j.article_id)
from publication pub
inner join journal j on pub.journal_id=j.journal_id
left join published p on j.article_id=p.article_id
group by pub.pub_id
You can use count(distinct ...) to count journals only once, despite the extra rows added by adding a join. That allows you to left join the published table:
select pub.pub_id, count(distinct j.journal_id), count(p.article_id)
from publication pub
inner join journal j on pub.journal_id=j.journal_id
left join published p on j.article_id=p.article_id
group by pub.pub_id