SQL查询汇总

时间:2020-03-30 00:47:16

标签: sql

我有两个桌子

单位

Unit_id
Unit_name
Unit_cost

组件

Component_id
Component_name
Unit_id

它们通过Unit_id链接在一起。

Unit_id = 1(名称为Unit 1 Name,成本为100)在Component中有许多记录。

Unit_id = 2的名称为Unit 2 Name,费用为200,在Component中也有许多记录。

因此,总成本取决于Component表中的记录数与unit_id中的Unit以及{{1 }}表。

我需要unit_price表中一个单位的单个Unit,该单位的总费用(Unit_name)最高。请注意,我只需要Unit,而不需要总费用。

在查询中最好使用Unit.Unit_cost吗?查询的外观如何?

2 个答案:

答案 0 :(得分:0)

我认为您想要这样的东西:

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;

答案 1 :(得分:0)

假设单位成本应乘以相关组成部分的数量:

let jd = JSONDecoder()
if let data = data, let resp = try? jd.decode(CallBack.self, from: data) {
    let nameOfNet = resp.NETWORK!.name
}

在内部查询名称和单位成本中,在外部查询mname中选择具有最大成本的单位。如果应该以其他方式计算成本,只需在查询中更改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 公式