[英]SQL query summation
I have two tables我有两张桌子
Unit单元
Unit_id
Unit_name
Unit_cost
Components成分
Component_id
Component_name
Unit_id
They are linked together by Unit_id
.它们通过
Unit_id
链接在一起。
Unit_id = 1
with name Unit 1 Name
with a cost of 100 has a number of records in Component
. Unit_id = 1
with name Unit 1 Name
成本为 100 的Unit 1 Name
在Component
有许多记录。
Unit_id = 2
with name Unit 2 Name
and a cost of 200 also has a number of records in Component
. Unit_id = 2
with name Unit 2 Name
和 cost 为 200 在Component
也有很多记录。
So the total cost depends on the number of records in the Component
table matched with the unit_id
in the Unit
, coupled with the unit_price
in the Unit
table.所以总成本取决于记录的数量
Component
与匹配表unit_id
在Unit
,再加上unit_price
在Unit
表。
I need the single Unit_name
of the one unit in the Unit
table that has the highest total cost ( Unit.Unit_cost
).我需要单
Unit_name
的一个单元在Unit
具有最高总成本(表Unit.Unit_cost
)。 Note I just need the Unit_Name
only, not total cost.注意我只需要
Unit_Name
,而不是总成本。
Would it be best to use a Top(1)
in the query?最好在查询中使用
Top(1)
吗? How would the query look?查询看起来如何?
I think you want something like this:我想你想要这样的东西:
select top (1) u.unit_name
from unit u join
component c
on c.unit_id = u.unit_id
group by u.unit_id, u.unit_name
order by sum(c.cost) desc;
assuming that unit cost should be multiplied by number of related components:假设单位成本应乘以相关组件的数量:
select top 1 name from(
select u.unit_name AS name, count(c.component_id) * u.unit_cost AS cost
from unit u join components c on u.unit_id = c.unit_id)
order by cost desc
In the inner query name and unit cost is calculated, at the outer query mname for unit that have max cost is selected.在计算内部查询名称和单位成本时,选择具有最大成本的单位的外部查询 mname。 If cost should be calculated in some other way just change
count(c.component_id) * u.unit_cost
formula in the query如果应该以其他方式计算成本,只需在查询中更改
count(c.component_id) * u.unit_cost
公式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.