i m trying to get this:
"Create a view that lists ALL foods with a total consumption for one week. This view is used to help order the food for the zoo animals to eat. Show the food id and name, along with the weekly consumption, the number of animals being fed with each food and the average consumption (weekly consumption divided by number of animals that eat that food) of the food by each animal."
below is my sql query:
SELECT a.foodID
,NAME
,b.qtyperday * 7 AS "weekly consumption"
,COUNT(animalID)
,AVG(( b.qtyperday * 7) / COUNT(animalID))
AS "average consumption"
FROM food a, feed b
WHERE a.foodID = b.foodID
GROUP BY foodID
i can't seem to be able to generate any data for the average consumption which is the final condition
, any solutions??
I believe you need to get the number of distinct animals for each food, e.g.:
SELECT a.foodID
,NAME
,b.qtyperday * 7 AS "weekly consumption"
,COUNT(DISTINCT animalID)
AS "animals eating this food"
,AVG(( b.qtyperday * 7) / COUNT(DISTINCT animalID))
AS "average consumption"
FROM food a, feed b
WHERE a.foodID = b.foodID
GROUP BY foodID
But for further help I think you need to post some sample data and some expected outputs.
Related
I want to use a simple private cashflow database. Nothing special.
Therefor I use a table "finance_flow", where I can put all my in- and outcomes.
Income -> amount > 0
outcome -> amount < 0
Table structure
table "finance_flow" with example-data
id
category_id
amount
date
note
int
int
float
timestamp
varchar
1
1
+60,00
5.2.23
use for xy
2
2
-10,00
8.2.23
to Tom for school
3
3
-8,96
8.2.23
milk, bread, cheese
table "category"
id
name
1
tips
2
kids
3
shop
Of course there is a correct foreign-key-constraint.
What I want:
I want some statistical data, for example:
-current status of my money
-total outcomes for each category
-procentual values of those would be nice
I know how to get the total current state:
SELECT sum(amount) as total FROM finance_flow
I know how to get the total per category
SELECT abs(sum(amount)) as total_per_cat, category.name
FROM finance_flow
LEFT JOIN category ON financeflow.cat_id = category.id
GROUP BY category_id [WHERE date = 'february']
(Here I use the function abs(x), because I am not interessted in the sign.
The where-clause is optional, I want this, if the basics are correct, for monthly reports.
How to get the procentual values?
Can I get all this stuff with one query? :)
Expected result:
procentual_per_cat = total_per_cut / total_income(february) * 100
where
total_per_cut = abs(sum(amount)) for category x
total_income(february) = 60
resulting table:
name
total_per_cat
procentual_per_cat
kids
10
16.67 %
shop
8.96
14.93 %
Calculating the percentage is the same a dividing by the total amount:
SELECT
abs(sum(amount)) as total_per_cat,
abs(sum(amount))/(select sum(amount) from finance_flow where amount>0) *100 as percentage,
category.name
FROM finance_flow
LEFT JOIN category ON finance_flow.cat_id = category.id
WHERE amount<0
GROUP BY category.name
see: DBFIDDLE
This might be difficult to explain. But Im trying to write a redshift sql query where I have want the count of organizations that fall into different market buckets. There are 50 markets. For example company x can be only be found in 1 market and company y can be found in 3 markets. I want to preface that I have over 10,000 companies to fit into these buckets. So ideally it would be more like, hypothetically 500 companies are found in 3 markets or 7 companies are found in 50 markets.
The table would like
Market Bucket
Org Count
1 Markets
3
2 Markets
1
3 Markets
0
select count(distinct case when enterprise_account = true and (market_name then organization_id end) as "1 Market" from organization_facts
I was trying to formulate the query from above but I got confused on how to effectively formulate the query
Organization Facts
Market Name
Org ID
Org Name
New York
15683
Company x
Orlando
38478
Company y
Twin Cities
2738
Company z
Twin Cities
15683
Company x
Detroit
99
Company xy
You would need a sub-query that retrieves the number of markets per company, and an outer query that summarises into a count of markets.
Something like:
with markets as (
select
org_name,
count(distinct market_name) as market_count
from organization_facts
)
select
market_count,
count(*) as org_count
from markets
group by market_count
order by market_count
If I follow you correctly, you can do this with two levels of aggregation. Assuming that org_id represents a company in your dataset:
select cnt_markets, count(*) cnt_org_id
from (select count(*) cnt_markets from organization_facts group by org_id) t
group by cnt_markets
The subquery counts the number of markets per company. I assumed no duplicate (ord_id, market_name) tuples in the table ; if that's not the case, then you need count(distinct market_name) instead of count(*) in that spot.
Then, the outer query just counts how many times each market count occurs in the subquery, which yields the result that you want.
Note that I left apart the enterprise_account column ,that appears in your query but not in your data.
I am looking for a way to add up averages in SQL. Here is an example of the data I have:
product avg_price
phone 104.28
car 1000.00
And I'm looking to build something like this:
product avg_price
[all] 544.27
phone 104.28
car 1000.00
The way I'm currently doing it is to store the count and sum in two different columns, such as:
product cnt total
phone 203 20,304.32
car 404 304,323.30
And from that get the average. However, I was wondering if it is possible in SQL to just 'keep the fraction' and be able to add them as needed. For example:
product avg_price
[all] [add the fractions]
phone 20,304.32 / 203
car 304,323.30 / 404
Or do I need to use two columns in order to get an average of multiple aggregated rows?
You don't need 2 columns to get the average, but if you want to display as a fraction then you will need both numbers. They don't need to be in 2 columns though.
select product, sum(total) ||'/'||sum(count)
from table a
join table b on a.product=b.product
union
select product, total ||'/'||count
from table a
join table b on a.product=b.product;
I'm creating a database for Formula 1 drivers/teams. The idea is to display the cost comparisons of team budgets vs team points and driver salaries, to see the effective cost per point for the top 10 teams.
E.g from 2015 info
Team Mercedes
Income received = euro 467.4m (sponsors 122m, partners 212.40m, tv 133m).
Points Scored = 703 (total from both drivers: Hamilton 381, Rosberg 322).
Effective Cost Per Point = 2,506,417.11
I have 3 datatables: One each for the team, the drivers, and a table to join tables 1&2 together, to then create the correct SELECT queries:
Table 'team'
teamid
teamname
sponsors
partners
tv
total
Table 'driver'
driverid
drivername
salary
points
Table 'driverteam'
teamid
driverid
totalbudget
totalpoints
I first need to get the sum of the sponsors,partners and tv so I have created the following SELECT statement:
$sql = "SELECT teamname, sum(sponsors+partners+tv) as total FROM team ORDER BY total DESC LIMIT 10";
I know how to get the salary and points from a driver:
$sql = "SELECT drivername, salary FROM driver ORDER BY salary DESC LIMIT 10";
$sql = "SELECT drivername, points FROM driver ORDER BY points DESC LIMIT 10";
Seems ok, but now comes my problem, how to get the SUM from table 1 and divide it by the points that the drivers have got in table 2.
My limited brain says I need a INNER JOIN using table 3 to get table 1 & 2 together, before performing the necessary divisions etc.
As there are 2 drivers per team, I need to divide the team total budget by each drivers' points, as well as the team total by both drivers points.
What SELECT queries do I need to achieve this?
I am new to SQL and I got stuck at this problem.
There are three separate tables needed for this problem, with relevant information as follows
copies table rentalrates table movies table
movienum rentalcode rentalcode rate movienum title yearreleased
1000 D D 10 1000 Matrix 2001
... D WN 12 ... ... ...
... WN WL 15 ... ... ...
So I am required to display the output of "the title and year released of the movie that has the lowest rental rate" using sub queries, and "order by" is not allowed here.
final output like
title yearreleased rate
matrix 2001 10
My trouble is I don't really know hot to compare the rate and select those movies of the lowest rates.
Any help or hint is extremely appreciated :)
thanks a lot!
This query:
select min(rate) from rentalrates
will yield the minimum rental rate. To go one step further, this query:
select m.title as title,
m.yearreleased as yearreleased,
r.rate as rate
from copies as c,
rentalrates as r,
movies as m
where c.movienum = m.movienum
and r.rentalcode = c.rentalcode
and r.rate = select min(rate) from rentalrates;
will display any movies (title, year, rate) where the rate is the lowest rate in the database.