So I have php SQL query that queries the floors and the total workstations on each floor.
config_location_workstation workstation asset_inventory
floor floor floor
workstation_number workstation_number workstation_number
workstation_name assigned_user
(production|non-production) machine_type
I have config_location_workstation table that consist of floor, workstation_number, workstation_name (Production, Non-Production).
Then, I have asset_workstation table that consist of floor, workstation_number, assigned_user, machine_type (Laptop, Desktop). workstation_number has all the users workstation number per floor.
I also have asset_inventory table that also has floor and workstation_number of each machine.
I was able to query the total count of workstations per floor. But I also need to pull up all the workstation_name that has 'Production' in it. I need to combine all the tables to produce one query to get the total count of each workstation, machines deployed to each floor, total head count per floor. I need to get the count of all users workstation number per workstation_name (Production, Non-Production).
This is the current code I have to pull up the floors and the total workstations.
$query=mysqli_query($conn,"SELECT workstation.floor, COUNT(*) TOTAL FROM ( SELECT floor FROM config_location_workstation UNION ALL SELECT floor FROM asset_workstation ) AS workstation GROUP BY floor ORDER BY floor");
I am expecting to output
+-------+-------------+------+------+------+------+-----+
| Floor | Head Count | Workstations| Machines Deployed |
+-------+-------------+------+------+------+------+-----+
| 6TH | 100 | 150 | 140 |
| 18TH | 200 | 250 | 200 |
| 19TH | 300 | 320 | 310 |
+-------+-------------+------+------+------+------+-----+
How am I going to do this in one query.
Your tables are not normalized: there appears to be duplicate information in all 3 tables. (unless workstation_number is not unique and floor/workstation_number is a composite key. I would advise against that...)
I would suggest a schema similar to this (assuming a many-to-many relationship between users and workstations):
Workstation User_Workstation User
id <- - workstation_id
workstation_number user_id - -> id
machine_type name
name
floor
Each of the fields in Workstation describe an attribute of a workstation. Any information you may have gathered from the other two tables is now in one place. Don't Repeat Yourself! Duplicate data is evil.
The goal is
I need to combine all the tables to produce one query to get the
total count of each workstation,
machines deployed to each floor,
total head count per floor.
I need to get the count of all users workstation number per workstation_name (Production, Non-Production).
Individually, these are a piece of cake. (And, if you're running a script to get your results, it's all you need)
select count(id) number_of_workstations
from Workstation;
select count(id) workstations_per_floor, floor
from Workstation
group by floor
select count(u.id) users_per_floor, floor
from Workstation w
inner join User_Workstation uw on w.id = uw.workstation_id
inner join User u on u.id = uw.user_id
-- optionally filter by production or non-production
-- where w.name = ?
group by w.floor
But your desired result seems to be something different:
+-------+-------------+------+------+------+------+-----+
| Floor | Head Count | Workstations| Machines Deployed |
+-------+-------------+------+------+------+------+-----+
| 6TH | 100 | 150 | 140 |
| 18TH | 200 | 250 | 200 |
| 19TH | 300 | 320 | 310 |
+-------+-------------+------+------+------+------+-----+
I'm guessing that Head Count is number of users per floor, Workstations is total workstations per floor, and Machines Deployed is... I have no idea. Production?
select floor, count(u.id) Head_Count, count(distinct w.id) Workstations, -- ??? as Machines_Deployed
from workstation w
left join user_workstation uw on w.id = uw.workstation_id
left join user on u.id = uw.user_id
group by w.floor
(I'll modify this based on feedback on what Machines Deployed is)
Related
I have two tables in SQL, one that contains product_id, products_name, department_name, and product_sales and one that has department_id, department_name, and over_head_costs.
I want to be able to find the sum of all sales (grouped by department_name in table 1) and subtract the over_head_costs from table 2 so that I know how profitable a department is. Then I want to output the information like:
department_id, department_name, over_head_costs, product/department sales, total_profit.
I've been searching for like 2-3 hours. I've messed around with joins (which I'm pretty sure is how to solve this) and found the SUM function, which achieves summing (but not by department) and honestly, even if I'd seen the solution I wouldn't know it. I'm just really struggling to understand SQL.
SELECT SUM(products.product_sales), department_id, departments.department_name, over_head_costs
FROM products, departments
WHERE products.department_name = departments.department_name;
This is my most recent query and the closest I've gotten, except it only returns one department (I currently have 3).
This is roughly what I’d like it to look like:
Table 1 (products):
ID ITEM DEPARTMENT SALES
1 Hammer Tools 40
2. Nails Tools 40
3. Keyboard Computer 80
Table 2 (departments):
ID DEPARTMENT COST
1 Tools 20
2. Computer 30
Output:
ID DEPARTMENT COST SALES PROFIT
1 Tools 20 80 60
2. Computer 30 80 50
I'm not really sure what else to try. I think I'm just not understanding how joins and such work. Any help would be greatly appreciated.
You can try to use SUM wiht group by in a subquery. then do join.
Query 1:
SELECT d.*,
t1.SALES,
(t1.SALES - d.COST)PROFIT
FROM (
SELECT DEPARTMENT,SUM(SALES) SALES
FROM products
GROUP BY DEPARTMENT
) t1 JOIN departments d on d.DEPARTMENT = t1.DEPARTMENT
Results:
| DEPARTMENT | COST | SALES | PROFIT |
|------------|------|-------|--------|
| Tools | 20 | 80 | 60 |
| Computer | 30 | 80 | 50 |
I am trying to calculate the stock by product a warehouse had over time. I have the information about today's stock, and also the amount of products sold and purchased by day. So, the calculation for yesterday values would be:
Yesterday_stock=Stock-yesterday_sold_quantity+yesterday_purchased_quantity. My problem is that i should save somewhere the amount of everyday's stock in order to calculate the stock of the previous day. I found that in order to do that i could use over sql clause with order by. But unfortunately, i have sql server 2008 and this is not a choice.
The tables are:
Prdamount which holds the current stock per product (StuPrdID ) and if it is blocked for some reason.
|-------------- |------------------|---------------
| StuPrdID | StuQAmount |prdBlockingReason
|---------------|------------------|-------------
| 12345| 16 |
|---------------|------------------|--------------
| 08889| 12 | expired
|---------------|------------------|------------
Table Moves which holds information about inserts and outputs of products. If MoveCase field has value equal 1 it is an output move, if it is a 2 it is a purchased quantity. Moves table dummy data:
|-------------- |--------------------- -|--------|-------
|MoveItemCode | MoveDate |MoveCase|MoveRealQty
|---------------|---------------------- |--------|-------
| 12345 |2018-06-24 00:00:00.000| 1 |14
|---------------|-----------------------|--------|--------
| 08889 |2018-06-24 00:00:00.000| 2 |578
|---------------|-----------------------|--------|--------
and table Product with information related with data:
|-------------- |------------------|
| PrdCode | PrdDespription |
|---------------|------------------|
| 12345| Orange juice|
|---------------|------------------|
| 08889| Chocolate|
|---------------|------------------|
I want an output like this:
|------------|--------------------- -|--------|--------------|------------
|Prdcode | PrdDescription |Stock |Stock 18/07/03|Stock 18/7/02
|------------|---------------------- |--------|--------------|------------
| 12345 |Orange Juice | 80 |50 34
|----------- |-----------------------|--------|--------------|------------
| 08889 |Chocolate | 45 |82 17
|------------|-----------------------|--------|--------------|-------------
this query gives me the running stock:
select
product.PrdCode,
product.PrdDescr,
SUM(StuQAmount) as Stock
from prdamount
left join product on (product.PrdID=prdamount.StuPrdID)
where prdamount.prdBlockingReason=' '
group by product.PrdCode,product.PrdDescr
order by product.PrdCode asc
This query gives me the quantity sold by product per day:
select
moves.MoveItemCode,
prd.PrdDescr,
moves.MoveDate,
SUM(MoveRealQty) as 'sold_quantity'
from moves
left join prd on (moves.MoveItemCode=product.PrdCode)
where (moves.MoveDate>'2018-06-01' and and moves.MoveCase=1)
group by moves.MoveItemCode,product.PrdDescr,moves.MoveDate
order by moves.MoveItemCode asc,moves.MoveDate asc
And this query gives me the quantity purchases by product per day:
select
moves.MoveItemCode,
prd.PrdDescr,
moves.MoveDate,
SUM(MoveRealQty) as 'Purchased_Quantity'
from Moves
left join product on (moves.MoveItemCode=product.PrdCode)
where (moves.MoveDate>'2018-06-01' and moves.MoveCase=2)
group by moves.MoveItemCode,product.PrdDescr,moves.MoveDate
order by moves.MoveItemCode asc,moves.MoveDate asc
I tried to combine these 3 queries into one using subqueries, but it didn't work. So how can i accomplish the result that i want? Sorry if the question is silly, i am a beginner in sql
try this,
select
product.PrdCode,
moves.MoveItemCode,
product.PrdDescr,
moves.MoveDate,
SUM( case when moves.MoveCase=1 then MoveRealQty else 0 end) as 'sold_quantity',
SUM( case when moves.MoveCase=2 then MoveRealQty else 0 end) as 'Purchased_Quantity',
(select SUM(StuQAmount) from prdamount where StuPrdID = product.PrdID and prdBlockingReason=' ')
from moves
left join product on (moves.MoveItemCode=product.PrdCode)
where (moves.MoveDate>'2018-06-01')
group by moves.MoveItemCode,product.PrdDescr,moves.MoveDate, product.PrdCode
order by moves.MoveItemCode asc,moves.MoveDate asc
I have 20 tables with same column with several example as below :
Australian GP
DRIVER | Points
================
HAM | 25
VET | 20
RIC | 15
Japanese GP
Driver | Points
==============
HAM | 25
VET | 20
RIC | 15
Malaysian GP
Driver | Points
RIC | 25
HAM | 20
VET | 15
I am planning to join all the 20 tables and all 20 driver datas as below for example :
Championship Standings
Driver | Points
HAM | 70
VET | 65
RIC | 50
Based on intense googling and massive confusion (I am bad at SQL since I have no spare time to learn outside my college), I have conclusion to use inner join and subquery such as below (which I don't know is it correct or a laughstock):
select driverid, point
from usa a, russia b, japan c
inner join (select driverid as Driver, sum(point) group by points);
I also thought that do I have to write 20 inner joins (as per example below) to connect the driver values between the tables?
(I created a table for Driver which contains driverid as primary key. All table that used to write points use foreign key from driver table)
Really really appreciate any helps regarding this case
You want union all`:
select driver, sum(points)
from ((select driver, points from usa) union all
(select driver, points from russia) union all
. . .
) c
group by driver;
Try this:
Select * From Table1
UNION ALL
Select * From Table2
UNION ALL
Select * From Table3
.
.
.
GROUP BY Driver
Where Table1, Table2, Table3 and so on are the names of your actual tables
I am using SQL and here is the scenario I am stuck with
Table A
SubscriptionID | Club | Sum_Of_Billings_Of_All_Month | EventID
Table B:
Cost | EventID
Table A left join Table B on EventID (To track the cost of each subscription)
Result
SubscriptionID | Club | Sum_Of_Billings_Of_All_Month | EventID | Cost
I want to break down the Sum_Of_Billings_Of_All_Month into per day billings. i.e. for each subscription, I want the breakdown of billings per day of the month. For that I will group by Sum_Of_Billings_Of_All_Month instead of subscriptionID.
Consequence
If I group by days of billing, upon joining I will get duplicates of subscriptionIDs and the eventIDs will be duplicated in rows multiple time which will then count the cost multiple times as well.
What I want:
In the same query, I want to be able to group by SubscriptionID so I can keep the unique subscriptions per row with their cost.
But one of the other requirement is that I want to know the breakdown of the billings as well to calculate the breakeven and other metrics in the same query
Here is the actual sample data
Table A
idCustomerSubscription | ClubID | EventId | BillingDate| FinalRevenue
33562784 | 56180001| 5y6m600np1fg | 5/31/2017 | 512
Table B
EventId |Cost
5y6m600np1fg |200
Table A join B left join on eventId (Group by SubscriptionID
idCustomerSubscription |ClubID |EventId |BillingDate| FinalRevenue | Cost
33562784 | 56180001 |5y6m600np1fg| 5/31/2017 | 512 |200
It serves the purpose because each subscription has one cost which is unique BUT it on the other hand, this kind of query will not give me breakdown of dates of billings (I need it for the breakeven calculation)
Table A join B left join on eventId (Group by billingdate
idCustomerSubscription| ClubID |EventId | BillingDate| FinalRevenue |Cost
33562784 | 56180001| 5y6m600np1fg |5/30/2017 |510 |200
33562784 | 56180001| 5y6m600np1fg |5/31/2017 |2 |200
This would give me the breakdown of the dates which i need for breakeven (510 on 30th and 2 on 31st) but it will make the cost duplicated (400 is the cost instead of 200)
I want to find out a SQL magic where I can keep the number of unique subcriptions per row and some way to track the billing dates of each subscriptions in the same query (without grouping it by date because it will make the rows duplicated). Is it possible ?
Perhaps some way where when the eventids are joined and its grouped by date, it doesnt duplicate the cost and count only one cost per eventid?
I hope you will get your desired result with below query. Try to modify your group by operation for mn (alias name) table.
select mn.idCustomerSubscription,mn.ClubID,mn.EventId,mn.BillingDate,mn.FinalRevenue,sq.cost
from tableA Mn left join (select idCustomerSubscription,max(cost) cost, min(billingDate) billingDate from tableA a left join tableB b on a.eventid=b.eventid group by idCustomerSubscription) sq on mn.idCustomerSubscription=sq.idCustomerSubscription and mn.billingDate=sq.billingdate
group by mn.idCustomerSubscription,mn.ClubID,mn.EventId,mn.BillingDate
I have a database with an producer and product table and I'm trying to find the producer(s) with the most expensive products on average. Basically I've got to find averages for each producers products then find the producers with the most expensive averages, in which there can be more than one producer with the most expensive average if they have the same average.
I've attempted with the code below but don't understand why its not working out?
Forget to mention this is for SQL.
EDIT:Forgot to say that the result should only display the most expensive averages
SELECT producerId, average
FROM (SELECT producerId, AVG(productPrice) AS average
FROM product NATURAL JOIN producer
GROUP BY producerId) AS averages
WHERE MAX(average)
Example:
producerID | average
1 | 10
2 | 8.5
3 | 10
4 | 9
5 | 8
Result:
producerID | average
1 | 10
3 | 10
If you want to get 3 most expensive producers, use query like this:
SELECT producerId, average
FROM (
SELECT pr.producerId, AVG(pr.productPrice) AS average
FROM product AS pp INNER JOIN producer AS pr ON pp.producerId = pr.producerId
GROUP BY pr.producerId
) AS T
ORDER BY average DESC
LIMIT 3;
For further information, please see the documentation: https://dev.mysql.com/doc/refman/5.0/en/select.html