Finding max - SQL - sql

I needed to print ( show ) the max of the table created by the following code:
SELECT name, SUM(cost)+SUM(DISTINCT stock*cost) AS result
FROM publishers
NATURAL JOIN editions
NATURAL JOIN shipments
NATURAL JOIN stock
GROUP BY name
I have tried using DESC but am not allowed to use it

SELECT MAX(result) from (SELECT name, SUM(cost)+SUM(DISTINCT stock*cost) AS result FROM publishers NATURAL JOIN editions NATURAL JOIN shipments NATURAL JOIN stock group by name )
This nested query should do if you only need max of result.

Related

Group By and Inner Join Together To Get Unique Values By Maximum Date

I have a table here in which I want to write a SELECT query in SQL Server that allows me to get the following:
For each unique combination of SalesPerson x Country, get only the rows with the latest Upload_DateTime
However, I am trying to do a group-by and inner join, but to no avail. My code is something like this:
SELECT t1.[SalesPerson], t1.[Country], MAX(t1.[Upload_DateTime]) as [Upload_DateTime]
FROM [dbo].[CommentTable] AS t1
GROUP BY t1.[SalesPerson], t1.[Country]
INNER JOIN SELECT * FROM [dbo].[CommentTable] as t2 ON t1.[SalesPerson] = t2.[SalesPerson], t1.[Country] = t2.[Country]
It seems like the GROUP BY needs to be done outside of the INNER JOIN? How does that work? I get an error when I run the query and it seems my SQL is not right.
Basically, this subquery will fetch the person, the country and the latest date:
SELECT
SalesPerson, Country, MAX(uplodaed_datetime)
FROM CommentTable
GROUP BY SalesPerson, Country;
This can be used on a lot of ways (for example with JOIN or with an IN clause).
The main query will add the remaing columns to the result.
Since you tried a JOIN, here the JOIN option:
SELECT
c.id, c.SalesPerson, c.Country,
c.Comment, c.uplodaed_datetime
FROM
CommentTable AS c
INNER JOIN
(SELECT
SalesPerson, Country,
MAX(uplodaed_datetime) AS uplodaed_datetime
FROM CommentTable
GROUP BY SalesPerson, Country) AS sub
ON c.SalesPerson = sub.SalesPerson
AND c.Country = sub.Country
AND c.uplodaed_datetime = sub.uplodaed_datetime
ORDER BY c.id;
Try out: db<>fiddle

SELECT "NOT IN", INNER JOIN and COUNT in SQL Query

I am trying to select which co-ordinates from OA table are NOT found in the CUSTOMER address table.
SELECT DISTINCT
OA.CO_ORDS
FROM
CUSTOMER
INNER JOIN
OA ON customer.address=oa.co_ords
ORDER BY ID ASC;
Returns the co-ordinates which ARE in the customer table. How do I return those that are not in the customer table?
Am I also able to COUNT how many of customers are is in each co-ordinate (The co-ords are not specific and not accurate, this is purely for query testing only)
SELECT DISTINCT
OA.CO_ORDS
FROM
CUSTOMER
INNER JOIN
OA ON customer.address=oa.co_ords
ORDER BY ID ASC;
We can use NOT EXISTS to find those co-ordinates which don't appear in the customer table:
SELECT co_ords
FROM oa
WHERE
NOT EXISTS
(SELECT 1 FROM customers
WHERE address = oa.co_ords)
ORDER BY id;
In order to count how many customers belong to a certain co-ordinate, we can use COUNT with GROUP BY, something like this:
SELECT c.address, COUNT(*)
FROM customers c
JOIN oa
ON c.address = oa.co_ords
GROUP BY c.address;
It could be better to count a specific column instead of *.
It could also be better to use an IN clause instead of JOIN the tables:
SELECT c.address, COUNT(*)
FROM customers c
WHERE address IN
(SELECT co_ords FROM oa)
GROUP BY c.address;
Such details depend on your exact table structure, you should please try this out or provide more details.
You could also do:
SELECT co_ords
FROM oa
MINUS
SELECT address
FROM customers;
which can sometimes be faster than doing an anti-join. Note that MINUS does a distinct on the resultset.

SQL dividing a count from one table by a number from a different table

I am struggling with taking a Count() from one table and dividing it by a correlating number from a different table in Microsoft SQL Server.
Here is a fictional example of what I'm trying to do
Lets say I have a table of orders. One column in there is states.
I have a second table that has a column for states, and second column for each states population.
I'd like to find the order per population for each sate, but I have struggled to get my query right.
Here is what I have so far:
SELECT Orders.State, Count(*)/
(SELECT StatePopulations.Population FROM Orders INNER JOIN StatePopulations
on Orders.State = StatePopulations.State
WHERE Orders.state = StatePopulations.State )
FROM Orders INNER JOIN StatePopulations
ON Orders.state = StatePopulations.State
GROUP BY Orders.state
So far I'm contending with an error that says my sub query is returning multiple results for each state, but I'm newer to SQL and don't know how to overcome it.
If you really want a correlated sub-query, then this should do it...
(You don't need to join both table in either the inner or outer query, the correlation in the inner query's where clause does the 'join'.)
SELECT
Orders.state,
COUNT(*) / (SELECT population FROM StatePopulation WHERE state = Orders.state)
FROM
Orders
GROUP BY
Orders.state
Personally, I'd just join them and use MAX()...
SELECT
Orders.state,
COUNT(*) / MAX(StatePopulation.population)
FROM
Orders
INNER JOIN
StatePopulation
StatePopulation.state = Orders.state
GROUP BY
Orders.state
Or aggregate your orders before you join...
SELECT
Orders.state,
Orders.order_count / StatePopulation.population
FROM
(
SELECT
Orders.state,
COUNT(*) AS order_count
FROM
Orders
GROUP BY
Orders.state
)
Orders
INNER JOIN
StatePopulation
StatePopulation.state = Orders.state
(Please forgive typos and smelling pistakes, I'm doing this on a phone.)

Display only maximum value in query with column meno - SQL

As mentioned in the title I want to display only row with maximum number, for this case it´s number 4 and nothing less.
select divak.MENO,count(divak.MENO)
from sledovanost
natural join tv_stanice
natural join divak
group by divak.meno
order by count(divak.MENO)desc;
My query
You can achieve this by a having-clause, in which you compare each MENO count with the maximum MENO count (retrieved by a subquery):
select divak.MENO,count(divak.MENO)
from sledovanost
natural join tv_stanice
natural join divak
group by divak.meno
having count(divak.MENO) = (
select (max(count(divak.MENO))
from sledovanost
natural join tv_stanice
natural join divak
group by divak.meno)
BTW: I'd change the query to join .. ON .. syntax; natural join, which connects tables on equally named attributes, bears the danger of "unintended connections" whenever the db schema changes.
Don't use natural join. It uses the names of the columns to match tables, and doesn't show the names in the query. It is a bug waiting to happen. Use USING or ON.
In Oracle, you would normally do this using row_number() or rank() depending on whether or not you wanted duplicates:
with t as (<your query here but name the second column>)
select t.*
from (select t.*, rank() over (order by cnt desc) as seqnum
from t
) t
where seqnum = 1;

SQL - count of number of times a foreign key appears in a table

Schema Info:
3 tables are concerned: SIGHTING, SPOTTER, AND ORG
SIGHTING references SPOTTER through FK SpotterId.
SPOTTER references ORG through FK OrgId.
I would like a query to return two columns; one for a list of ORG.OrgName, and another for the respective total count of Spotter_ID appearances in SIGHTINGS for the corresponding ORG.OrgID.
What I have done below returns the incorrect counts for each row returned:
SELECT ORG.ORG_NAME AS ORG_NAME,
(SELECT COUNT(SIGHTINGS.SPOTTER_ID)
FROM SIGHTINGS
, SPOTTERS
WHERE SIGHTINGS.SPOTTER_ID = SPOTTERS.SPOTTER_ID
AND SPOTTERS.ORG_ID=ORG.ORG_ID) AS ORG_COUNT
FROM ORG;
It seems that you only need aggregation:
SELECT COUNT(1), orgName
FROM SIGHTING
INNER JOIN SPOTTER USING (spotterId)
INNER JOIN ORG USING (orgId)
GROUP BY orgName
This is simple aggregation, but you only need one JOIN:
select o.orgname, count(*) as numSpotters
from org o join
spotters s
on o.orgId = s.orgId
group by o.orgname;
Note: If you want all organizations, even those with no spotters, then use left join instead of join.