从选择查询中按列选择非重复项

时间:2018-12-31 21:19:24

标签: mysql sql

我已经看过stackoverflow了,但是没有运气,所以这里什么也没做。

我有一张桌子,上面有关于房屋位置的某些信息,我选择这些位置并计算房屋坐标与所需坐标之间的距离,然后按距离递增的顺序排序;

SELECT id, type, distance FROM (SELECT b.id, b.type, b.x, b.y, b.z, 
    SQRT(POWER(ABS(1654.5413 - b.x), 2) + POWER(ABS(-2293.7571 - b.y), 2) + POWER(ABS(-1.1996 - b.z), 2)) AS "distance" 
        FROM businesses b ORDER BY distance ASC) as T;

示例输出;

+------+------+------------------------+
| id   | type | distance               |
+------+------+------------------------+
| 1953 |    2 | 0.00004489639611771451 |
|    2 |  100 |      8.757256937390904 |
| 1959 |    2 |      8.999959765646956 |
| 1960 |    2 |     10.499959765643807 |
| 1961 |    2 |     11.999959765641446 |
| 1962 |    2 |     13.499959765639607 |
| 1963 |    2 |     14.999959765638138 |
| 1964 |    2 |     16.499959765636934 |
| 2055 |    3 |      17.11486010149676 |
| 2054 |    1 |     17.751048488860313 |
| 1965 |    2 |     17.999959765635932 |
| 1966 |    2 |     19.499959765635083 |
| 1967 |    2 |     20.999959765634358 |
| 2056 |    5 |      22.26658275782834 |
| 1968 |    2 |     22.499959765633726 |
| 1969 |    2 |     23.999959765633175 |
| 2057 |    5 |     24.054132659013334 |
| 1970 |    2 |      25.49995976563269 |
| 2058 |    5 |     26.001138245767084 |
| 2061 |    4 |     26.853239370669378 |
| 1971 |    2 |      26.99995976563226 |
| 1972 |    2 |      28.49995976563187 |
| 2060 |    5 |      28.55999771765475 |
| 1973 |    2 |     29.999959765631523 |
| 2059 |    5 |     31.414688663981224 |
| 1974 |    2 |     31.499959765631207 |
|    1 |  100 |      121468.4587678613 |
+------+------+------------------------+

我想对这些结果做的只是通过选择“类型”列的非重复项来抓取一行,就像这样(并保持距离ASC顺序);

+------+------+------------------------+
| id   | type | distance               |
+------+------+------------------------+
| 1953 |    2 | 0.00004489639611771451 |
|    2 |  100 |      8.757256937390904 |
| 2055 |    3 |      17.11486010149676 |
| 2054 |    1 |     17.751048488860313 |
| 2056 |    5 |      22.26658275782834 |
| 2061 |    4 |     26.853239370669378 |
+------+------+------------------------+

如果我尝试“选择不同的类型”,它将不会保持行的顺序,并且将始终选择“类型”的最后一个重复项(我想我说的没错)。

我将如何获得理想的结果?

0 个答案:

没有答案