多级查询从第二个子查询获取值以驱动父元素

时间:2017-10-20 17:27:16

标签: mysql sql

我正在尝试获得一个多级查询,让我看起来像是一个简单的答案。我有2500行数据反对邮政编码。每行包含邮政编码,人员姓名首字母,主要成本和二次成本。我希望根据主要成本获得最低的邮政编码成本 - 这一点很容易 - 但是如果同一邮政编码中有多个人具有相同的主要成本,我需要返回次要成本最低的人。 例如:

postcode, initials, p_cost, s_cost
AB12    , DS      , 100   , 0
AB12    , JH      , 100   , 40
AB12    , SS      , 120   , 0

因此,我想推出DS,因为他们的初级成本与JH一样最低,但他们的二级成本也是最低的。 这是我到目前为止的SQL:

SELECT initials, min(s_cost) FROM
    (SELECT * FROM MyTable
     WHERE postcode = 'AB12'
     and p_cost = 
        (select min(p_cost) from MyTable 
         WHERE postcode = 'AB12'));

我也尝试过:

SELECT * FROM MyTable
WHERE postcode = 'AB12' 
and p_cost = (select min(p_cost) 
               from MyTable 
               WHERE postcode = 'AB12'
               and s_cost = (select min(s_cost) 
                                     from MyTable 
                                     WHERE postcode = 'AB12'));

有人可以把我从我的痛苦中解脱出来,它应该很简单,但是自从我上次写作和愤怒的SQL已有15年了,这真的让我烦恼。

感谢大家的帮助: - )

3 个答案:

答案 0 :(得分:1)

您是否尝试过使用加入条件作为过滤器来加入自己的表格?

select mt1.* 
from mytable mt1
left join mytable mt2 
    on mt1.postcode = mt2.postcode 
        and ( mt1.p_cost < mt2.p_cost 
         or (mt1.p_cost = mt2.p_cost and mt1.s_cost < mt2.s_cost)
        )
where mt1.postcode = 'AB12'

此代码未经测试。

答案 1 :(得分:1)

也许你可以试试这个。

Select * 
from MyTable 
where postcode = 'AB12' 
order by p_cost asc, s_cost asc 
limit 1;

答案 2 :(得分:0)

首先,您需要计算每个邮政编码的最低p_cost

 SELECT postcode, MIN(primary_cost) as min_primary_cost
 FROM MyTable 
 WHERE postcode = 'AB12'

现在您需要计算secondary_cost的最小值,但是要根据主要成本计算

 SELECT primary_cost, MIN(secondary_cost) as min_primary_cost
 FROM MyTable 
 WHERE postcode = 'AB12'
 GROUP BY primary_cost

现在加入

<强> SQL DEMO

SELECT *
FROM YourTable
JOIN ( SELECT postcode, MIN(primary_cost) as min_primary_cost
       FROM YourTable 
       WHERE postcode = 'AB12'
     ) as p_cost
ON YourTable.postcode = p_cost.postcode
AND YourTable.primary_cost = p_cost.min_primary_cost
JOIN ( SELECT primary_cost, MIN(secondary_cost) as min_secondary_cost
       FROM YourTable 
       WHERE postcode = 'AB12'
       GROUP BY primary_cost
     ) as s_cost
  ON YourTable.primary_cost = s_cost.primary_cost
 AND YourTable.secondary_cost= s_cost.min_secondary_cost
WHERE postcode = 'AB12'