sql group by two column with min condition

时间:2016-06-16 19:40:16

标签: mysql sql mysqli

我有下一张桌子,

| ID |ID2  | price|
+----+---+----+
| A  | AA   | 7 |
| B  | AA   | 3 |
| C  | AA   | 4 |
| D  | BB   | 7 |
| I  | BB   | 2 |
| F  | BB   | 3 |
| G  | CC   | 9 |
| E  | CC   | 4 |
| K  | CC   | 1 |

+----+---+---+

我需要下一张桌子 按ID2分组,具有最小字段价格和相应的最小价格字段ID1

| ID1 | ID2 | min_price |
+----+---+---+----------
| B  | AA   | 3         |
| I  | BB   | 2         |
| K  | CC   | 1         |
+----+---+---+---------

4 个答案:

答案 0 :(得分:1)

select a.id, a.id2, a.price from #yourtable a
 join 
    (
    select  id2, min(price) AS price 
    from #yourtable
    group by id2 
    )b 
 on a.id2=b.id2 and a.price=b.price

答案 1 :(得分:0)

SELECT *
FROM
    #table t
    INNER JOIN (
       SELECT
          ID2
          ,MIN(price) as min_price
       FROM
          #table
       GROUP BY
          ID2
    ) g
    ON t.ID2 = g.ID2
    AND t.price = g.min_price

步骤1找到最低价格,步骤2回过头来获取匹配的原始记录以获取ID。还有其他方法可以做到这一点。

请注意,如果您的数据集包含具有相同价格的同一ID2中的2条记录,则将始终返回多于1条记录。

答案 2 :(得分:0)

根据您的解释,我们需要按ID2分组并获得最低价格及其相应的ID。 这是同一个

的查询
SELECT id,
  id2,
  price
FROM NEXT
WHERE (price,id2) IN
  (SELECT MIN(price), id2 FROM NEXT GROUP BY id2
  );

答案 3 :(得分:0)

http://sqlfiddle.com/#!9/295702/2

charexists() { test "$(echo "$2" | tr -cd "$1")" ;}