在两列(单独)上区分,在另一列上区分MIN

时间:2013-02-26 03:28:43

标签: sql sql-server tsql distinct

我试图将这个问题从骨头上剥下来;我希望我仍然抓住了我在原始查询中想要达到的目标的本质!

  • 可以找到生成表格和数据的代码here
  • SQL风格 Microsoft SQL Server 2000 (虽然我一直在MySQL上运行这个剥离的测试用例)

原始表格

+-----------+----------+----------+
| master_id | slave_id | distance |
+-----------+----------+----------+
|         1 |        1 | 0.1      |
|         1 |        3 | 10       |
|         2 |        2 | 3        |
|         3 |        2 | 2        |
+-----------+----------+----------+

需要说明

我想选择slave_id master_idMIN(distance)无重复 master_idslave_id。< / p>

所需的结果表

+-----------+----------+----------+
| master_id | slave_id | distance |
+-----------+----------+----------+
|         1 |        1 | 0.1      |
|         3 |        2 | 2        |
+-----------+----------+----------+

我的尝试

SELECT
        join_table.master_id,
        join_table.slave_id,
        join_table.distance
    FROM join_table
    INNER JOIN
        (
            SELECT
                slave_id,
                MIN(distance) AS distance
            FROM join_table
            GROUP BY slave_id
        ) AS self_join
    ON self_join.slave_id = join_table.slave_id
    AND self_join.distance = join_table.distance

我的尝试出了什么问题

此查询会生成master_id

的重复项

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

这应该给出正确的结果:

select distinct t.master_id,
  t.slave_id,
  t.distance
from join_table t
inner join
(
  SELECT ID, min(Distance) dist
  FROM 
  (
    SELECT master_ID ID, MIN(distance) AS Distance
    FROM join_table
    GROUP BY master_ID
    UNION
    SELECT slave_ID ID, MIN(distance) AS Distance
    FROM join_table
    GROUP BY slave_ID
  ) src
  GROUP BY ID
) md
  on t.distance = md.dist
  and (t.master_id = md.id or t.slave_id = md.id)

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

如果我说得对,我会这样做:

SELECT DISTINCT t.master_id
   ,t.slave_id
   ,t.distance
FROM your_table t
   INNER JOIN 
   (
      SELECT master_id id, min(distance) distance
      FROM your_table
      GROUP BY master_id

      UNION

      SELECT slave_id id, min(distance) distance
      FROM your_table
      GROUP BY slave_id

   ) sub
   ON (sub.id = t.master_id AND sub.distance = t.distance)
     OR (sub.id = t.slave_id AND sub.distance = t.distance)