SQL query summation

后端 未结 2 1177
再見小時候
再見小時候 2021-01-29 07:44

I have two tables

Unit

Unit_id
Unit_name
Unit_cost

Components

Component_id
Component_         


        
相关标签:
2条回答
  • 2021-01-29 08:05

    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. If cost should be calculated in some other way just change count(c.component_id) * u.unit_cost formula in the query

    0 讨论(0)
  • 2021-01-29 08:31

    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;
    
    0 讨论(0)
提交回复
热议问题