Join a table to bring in another field [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 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

Related

3 Table Join SQL Big Query

I'm new to SQL joins so bear with me, what I'm trying to do is list out student test scores by week added up per student. The query I have is,
SELECT
agg.Week,
meta.Category,
agg.Student,
meta.Funding,
agg.Test_Results,
agg.Test_Points,
phy.Test_Results,
phy.Test_Points
FROM Agriculture agg
INNER JOIN metadata meta
ON meta.Student_ID = agg.Student_ID
INNER JOIN Physics phy
ON phy.Student_ID = agg.Student_ID
WHERE agg.Week BETWEEN '1' AND '5'
To me this looks correct, but for some reason what is happening is the Test_Results and Test_Points are duplicating themselves over and over and I'm not sure how to fix it. What I mean by duplicating is, since the points are the same 120 each week, a student(9) will score a 95, that 95 will repeat itself for that same student over and over again. I'm not sure if I need to have a subquery added to the INNER JOINS or not.
Tables are:
metadata --> (Category, Funding, Student_ID) (One to many comparison table)
Physics --> (Test_Results, Test_Points, Student_ID) (Many to many)
Agriculture --> (Week, Student, Test_Results, Test_Points, Student_ID) (Many to Many)
Again, I'm new to joins so if you need more information please let me know.
You join the table by using Student_ID. If there is more than one corresponding row in metadata for the same Student_ID from Agriculture the resultset will show duplicates.
The same goes for table Physics.
for example : You have 10 rows in table Agriculture for a Student_ID and 2 rows in metadata with the same Student_ID, you will get 20 rows if you join the tables.
You can indeed use subqueries to reduce the number of rows per Studen_ID in metadata and Physics and join on those subselects.
You can simply use DISTINCT keyword for agg.Student.

How to get desired result set by SQL query [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.
select * from employee
UNIT_ID PARENT_UNIT TOT_EMP
------- ----------- -------
Oracle IT 10
SAP IT 20
IT PST 30
HRGA FA 5
FA PST 12
How to get output as:
IT 60
ORACLE 10
SAP 20
HRGA 5
FA 17
select a.name, sum(a.tot_emp)
from
(
select unit_id as name, sum(tot_emp) as tot_emp
from employee
group by unit_id
UNION
select parent_id as name, sum(tot_emp) as tot_emp
from employee
group by parent_id
) as a
where exists (select null
from employee e
where e.unit_id = a.name)
group by name;
But this is not a real recursive query (which seems to be what you need), it will work with your sample, but maybe not with real datas (but we don't know the deepness of your hierarchy).
i don't know some detalis. can be in the column UNIT_ID to times the same name?
if not, this is good query:
select e1.UNIT_ID, SUM(TOT_EMP) AS TOT_EMP
from emploee e1
innner join emploee e2
on e1.UNIT_ID = E2.PARENT_UNIT
group by e1.UNIT_ID
if can be same name in the column UNIT_ID, look in the answer of Raphaƫl Althaus. it's good answer.
This is Oracle query:
SELECT unit_id, SUM(total_emp) FROM stack_test
GROUP BY unit_id
/
UNIT_ID SUM(TOTAL_EMP)
-------- --------------
SAP 50
HRGA 15
ORACLE 30
It is always good idea to create tables and populate them with values in your posts...

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

SQL INNER JOIN DISTINCT [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have the tables PRODUCTS and LISTINGS. When doing the following query:
SELECT DISTINCT *
FROM products
INNER JOIN listings
ON products.product_number=listings.product_number
This is the "search" functionality:
WHERE products.product_number !=''
AND listings.monthly_price BETWEEN '0' AND '10'
This returns a double entry of one of the product listings. Why isn't DISTINCT working?
EDIT
Products:
product_number, make, model model_number, colour, processor, battery_standby, battery_talk, camera, flash, screen_size, screen_res, memory
Listings:
listing_number, featured, date, member_id, network, length, product_number, monthly_price, minutes, texts, data, image1
Essentially I'd like to create result rows matching the listings tables via their PRODUCT_NUMBER to the product table. It's for a search function of a phone listings website to be more precise.
To be much more specific, the search function uses the products table to search, then the listings table to show the useful information about the phone listing.
ANSWER
SELECT DISTINCT *
FROM listings
INNER JOIN products
ON products.product_number=listings.product_number
The above did the trick; simply swapping the tables round. I also inserted a few more rows into listings, and the "problem" vanished. Even if it's not solved, it isn't happening anymore... Not sure what the problem was.
I believe you're just expecting something from DISTINCT that doesn't work that way....
Assume you have a table Products with ID and Name, and table Listings with ID, ProductID (FK to Products), andListing_date` (just to make things a bit simpler here....)
Assume furthermore that your table Products has entries:
ID Name
1 Foobar
2 Bazfoo
and table Listings has entries
ID ProductID ListingDate
1 1 2012-01-01
2 1 2012-03-01
3 2 2012-04-01
If you join these two tables and apply a DISTINCT
SELECT DISTINCT ProdID = p.ID, p.Name, ListingID = l.ID, l.ListingDate
FROM dbo.Products p
INNER JOIN dbo.Listings l ON l.ProductID = p.ID
what results do you expect??
The result will be:
ProdID Name ListingID ListingDate
1 Foobar 1 2012-01-01
1 Foobar 2 2012-03-01
2 Bazfoo 3 2012-04-01
The DISTINCT keyword is applied to all columns - only if all columns in the result set are identical, then a row will be filtered out.
From your comments, I'm led to believe that you're expecting that the "duplicate" product with ID = 1 and Name = Foobar should be excluded. This is NOT the case - see the result set - if you look at all four columns, those two rows with ProdID = 1 are NOT identical - therefore, they will both show up.
That's just the way the DISTINCT keyword is defined to work.
If you want to "filter out" the duplicate product with ID=1 - which of the two entries in the Listings table are you expecting to be shown in the result set?
If there is a record where 2 listings joins a single product then this would produce what you are seeing:
The select distinct is done on the result of the inner join
I'd use the common join value to select * from each table and see the results
HTH
Ian

How to write a SQL Query for the following [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 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