SQL query about competitors and placings - sql

I'm really at a loss for a good title, suggestions are welcome.
I have two tables, one is a table of competitors, the other is a table with three fields
event
competitor
placing - a number representing what place they got at the given event
My goal is, given a set of placings, return all the competitors that achieved that placing at least once at any event.
So, for example, I might want to see all the competitors that placed 1st or 2nd at something.

Not sure how your tables are defined
But could try this sql
SELECT
c.id,
e.event,
e.placing
FROM competitor_table c
LEFT JOIN event_table e
ON e.competitor_id = c.id
WHERE e.placing in (placings_set)
GROUP BY c.id,e.event, e.placing

Related

Access SQL Lookup - Dropdown Columns

I have looked for a similar issue with no luck. Maybe I don't know the right term to search for.
This seems so simple, but I just can't get it after spending many hours trying different approaches.
I have a dropdown to select contracts which shows some ids for related fields. How can I get those IDs to show the value of another column.
SELECT tbl_contracts.ID, tbl_contracts.contract_name, tbl_contracts.firm_id, tbl_contracts.agency_id
FROM tbl_contracts;
image of dropdown
I would like the IDs shown for agency_id and firm_id to list the company_name from their respective table "tbl_firm_agencies" where the tbl_contracts looks them up from. I've tried INNER JOINS but when I do, I can only line items to show when both agency AND firm exist, so my dropdown get cut off quite a bit.
Simply LEFT JOIN to those lookup tables as opposed to INNER JOIN. Adjust table and field names to actual ones in query below. Also, the parentheses are required in MS Access SQL.
SELECT c.ID, c.contract_name, f.firm_name, a.agency_name
FROM (tbl_contracts c
LEFT JOIN tbl_firms f
ON c.firm_id = f.firm_name)
LEFT JOIN tbl_agencies a
ON c.agency_id = a.agency_name;

Refer to different id's within the same query in SQL

I need to brind a lot of columns from several tables using LEFT JOIN. My starting point is the orders table and I bring the vendor name from the "Address_table". Then I add another table with order details and then the shipping information of each order detail.
My problem is that I need to bring a different record from "Address_table" to refer onether id's detailed in shipment table as of "origin_id" and "destination_id".
In other words, "address_id", "origin_id" and "destination_id" are all records from "Address_table". I brought the first one related to the vendor, how can I retrieve the other two?
Example
Thanks in advance
Your question is not exactly clear in terms of the tables and their relationships. It is, however, clear what the problem is. You need to join against the same table twice using different columns.
In order to do that you need to use table aliases. For example, you can do:
select *
from shipment s
left join address_table a on a.address_id = s.origin_id
left join address_table b on b.address_id = s.destination_id
In this example the table address_table is joined twice against the table shipment; the first time we use a as an alias, the second time b. This way you can differentiate how to pick the right columns and make the joins work as you need them to.

How to count different rows and put them all in same table in SQL?

I want to count how many people are applied for each category in my database and put all of those counts in one table. I don't have exact idea how should I do that. I've done it already like this but I want to have all in one query, and not to do it like this for each category.
select
count(cc.fk_id_candidates) as 'category A'
from candidate_category cc, candidate c, category cat
where c.id=cc.fk_id_candidates and cc.fk_id_category=cat.id and category.name='A';
From that code I get number of people applied for category A as an output, which is correct, but I just need the same info for other categories too. I tried with case but it's not working right.
Thank you.
You would typically add a group by clause on the category name and/or id:
select cat.category.name, count(*) cnt
from candidate_category cc
inner join candidate c on c.id = cc.fk_id_candidates and
inner join category cat on cc.fk_id_category = cat.id
group by cat.id, cat.category.name;
Note that I changed your query to use standard joins (with the on keyword) rather than implicit joins (with commas in the from clause and conditions in the where clause) - this old syntax should not be used in new code.
As i understand you have three tables:
- candidate_category cc,
- candidate c,
- category cat
Also, you have Created below relationship using the REFERENCES:
where c.id=cc.fk_id_candidates
and cc.fk_id_category=cat.id
and category.name='A;
Now, you must have all the three tables in one table already and you can view it by:
and this is very important step to find a common column where you can filter it and find the proper data you want.
Select *
from candidate_category cc,
candidate c,
category cat
where c.id=cc.fk_id_candidates
and cc.fk_id_category=cat.id

SQL Counting and Joining

I'm taking a database course this semester, and we're learning SQL. I understand most simple queries, but I'm having some difficulty using the count aggregate function.
I'm supposed to relate an advertisement number to a property number to a branch number so that I can tally up the amount of advertisements by branch number and compute their cost. I set up what I think are two appropriate new views, but I'm clueless as to what to write for the select statement. Am I approaching this the correct way? I have a feeling I'm over complicating this bigtime...
with ad_prop(ad_no, property_no, overseen_by) as
(select a.ad_no, a.property_no, p.overseen_by
from advertisement as a, property as p
where a.property_no = p.property_no)
with prop_branch(property_no, overseen_by, allocated_to) as
(select p.property_no, p.overseen_by, s.allocated_to
from property as p, staff as s
where p.overseen_by = s.staff_no)
select distinct pb.allocated_to as branch_no, count( ??? ) * 100 as ad_cost
from prop_branch as pb, ad_prop as ap
where ap.property_no = pb.property_no
group by branch_no;
Any insight would be greatly appreciated!
You could simplify it like this:
advertisement
- ad_no
- property_no
property
- property_no
- overseen_by
staff
- staff_no
- allocated_to
SELECT s.allocated_to AS branch, COUNT(*) as num_ads, COUNT(*)*100 as ad_cost
FROM advertisement AS a
INNER JOIN property AS p ON a.property_no = p.property_no
INNER JOIN staff AS s ON p.overseen_by = s.staff_no
GROUP BY s.allocated_to;
Update: changed above to match your schema needs
You can condense your WITH clauses into a single statement. Then, the piece I think you are missing is that columns referenced in the column definition have to be aggregated if they aren't included in the GROUP BY clause. So you GROUP BY your distinct column then apply your aggregation and math in your column definitions.
SELECT
s.allocated_to AS branch_no
,COUNT(a.ad_no) AS ad_count
,(ad_count * 100) AS ad_cost
...
GROUP BY s.allocated_to
i can tell you that you are making it way too complicated. It should be a select statement with a couple of joins. You should re-read the chapter on joins or take a look at the following link
http://www.sql-tutorial.net/SQL-JOIN.asp
A join allows you to "combine" the data from two tables based on a common key between the two tables (you can chain more tables together with more joins). Once you have this "joined" table, you can pretend that it is really one table (aliases are used to indicate where that column came from). You understand how aggregates work on a single table right?
I'd prefer not to give you the answer so that you can actually learn :)

Where are Cartesian Joins used in real life?

Where are Cartesian Joins used in real life?
Can some one please give examples of such a Join in any SQL database.
just random example. you have a table of cities: Id, Lat, Lon, Name. You want to show user table of distances from one city to another. You will write something like
SELECT c1.Name, c2.Name, SQRT( (c1.Lat - c2.Lat) * (c1.Lat - c2.Lat) + (c1.Lon - c2.Lon)*(c1.Lon - c2.Lon))
FROM City c1, c2
Here are two examples:
To create multiple copies of an invoice or other document you can populate a temporary table with names of the copies, then cartesian join that table to the actual invoice records. The result set will contain one record for each copy of the invoice, including the "name" of the copy to print in a bar at the top or bottom of the page or as a watermark. Using this technique the program can provide the user with checkboxes letting them choose what copies to print, or even allow them to print "special copies" in which the user inputs the copy name.
CREATE TEMP TABLE tDocCopies (CopyName TEXT(20))
INSERT INTO tDocCopies (CopyName) VALUES ('Customer Copy')
INSERT INTO tDocCopies (CopyName) VALUES ('Office Copy')
...
INSERT INTO tDocCopies (CopyName) VALUES ('File Copy')
SELECT * FROM InvoiceInfo, tDocCopies WHERE InvoiceDate = TODAY()
To create a calendar matrix, with one record per person per day, cartesian join the people table to another table containing all days in a week, month, or year.
SELECT People.PeopleID, People.Name, CalDates.CalDate
FROM People, CalDates
I've noticed this being done to try to deliberately slow down the system either to perform a stress test or an excuse for missing development deliverables.
Usually, to generate a superset for the reports.
In PosgreSQL:
SELECT COALESCE(SUM(sales), 0)
FROM generate_series(1, 12) month
CROSS JOIN
department d
LEFT JOIN
sales s
ON s.department = d.id
AND s.month = month
GROUP BY
d.id, month
This is the only time in my life that I've found a legitimate use for a Cartesian product.
At the last company I worked at, there was a report that was requested on a quarterly basis to determine what FAQs were used at each geographic region for a national website we worked on.
Our database described geographic regions (markets) by a tuple (4, x), where 4 represented a level number in a hierarchy, and x represented a unique marketId.
Each FAQ is identified by an FaqId, and each association to an FAQ is defined by the composite key marketId tuple and FaqId. The associations are set through an admin application, but given that there are 1000 FAQs in the system and 120 markets, it was a hassle to set initial associations whenever a new FAQ was created. So, we created a default market selection, and overrode a marketId tuple of (-1,-1) to represent this.
Back to the report - the report needed to show every FAQ question/answer and the markets that displayed this FAQ in a 2D matrix (we used an Excel spreadsheet). I found that the easiest way to associate each FAQ to each market in the default market selection case was with this query, unioning the exploded result with all other direct FAQ-market associations.
The Faq2LevelDefault table holds all of the markets that are defined as being in the default selection (I believe it was just a list of marketIds).
SELECT FaqId, fld.LevelId, 1 [Exists]
FROM Faq2Levels fl
CROSS JOIN Faq2LevelDefault fld
WHERE fl.LevelId=-1 and fl.LevelNumber=-1 and fld.LevelNumber=4
UNION
SELECT Faqid, LevelId, 1 [Exists] from Faq2Levels WHERE LevelNumber=4
You might want to create a report using all of the possible combinations from two lookup tables, in order to create a report with a value for every possible result.
Consider bug tracking: you've got one table for severity and another for priority and you want to show the counts for each combination. You might end up with something like this:
select severity_name, priority_name, count(*)
from (select severity_id, severity_name,
priority_id, priority_name
from severity, priority) sp
left outer join
errors e
on e.severity_id = sp.severity_id
and e.priority_id = sp.priority_id
group by severity_name, priority_name
In this case, the cartesian join between severity and priority provides a master list that you can create the later outer join against.
When running a query for each date in a given range. For example, for a website, you might want to know for each day, how many users were active in the last N days. You could run a query for each day in a loop, but it's simplest to keep all the logic in the same query, and in some cases the DB can optimize the Cartesian join away.
To create a list of related words in text mining, using similarity functions, e.g. Edit Distance