通过id sql server选择具有最小值[col1]的最小值[col1]的行

时间:2017-11-29 08:30:16

标签: sql-server max distinct multiple-columns min

示例数据 MAIN_TABLE:

+-----+--------+-------+
| ID  | HEIGHT | STOCK |
+-----+--------+-------+
| ID1 |    180 |   680 |
| ID1 |    170 |   680 |
| ID1 |    130 |   360 |
| ID2 |    250 |   420 |
| ID2 |    190 |   420 |
| ID2 |     70 |   120 |
| ... |   ...  |  ...  |
+-----+--------+-------+

我需要选择具有最大STOCK和最小高度的不同ID行。

期望的结果是:

+-----+--------+-------+
| ID  | HEIGHT | STOCK |
+-----+--------+-------+
| ID1 |    170 |   680 |
| ID2 |    190 |   420 |
| ... |   ...  |  ...  |
+-----+--------+-------+

查询代码,我正在使用它来实现它:

WITH MAX_STOCK (ID, maxstock) as
(
    select ID, max(STOCK) as maxstock
    from MAIN_TABLE
    group by ID
),
TABLE_STOCK (ID, HEIGHT, STOCK) AS
(
    select a.ID, a.HEIGHT, a.STOCK
    from MAIN_TABLE a join MAX_STOCK b
    on a.ID= b.ID and a.STOCK = b.maxstock
),
MIN_HEIGHT (ID, minheight) as
(
    select ID, min(HEIGHT) as minheight
    from TABLE_STOCK
    group by ID
),
TABLE_HEIGHT (ID, HEIGHT, STOCK) AS
(
    select a.ID, a.HEIGHT, a.STOCK
    from TABLE_STOCK a join MIN_HEIGHT b
    on a.ID= b.ID and a.HEIGHT = b.minheight
)

如果我选择任何表MAX_STOCK,TABLE_STOCK,MIN_HEIGHT,

我的结果是1-2秒。

但是当选择TABLE_HEIGHT时,这将是我想要的结果,

正在执行6分钟+对600行数据无应答

我应该如何编写此查询以便在合理的时间内得到结果?

0 个答案:

没有答案