简体   繁体   English

SQL仅选择具有Where Condition的列上具有最小值的行

[英]SQL Select only rows with Minimum Value on a Column with Where Condition

Table: 表:

| id | productId | orderIndex | rejected |
------------------------------------------
| 1  |  1        |   0        |   1      |
| 2  |  1        |   1        |   0      |
| 3  |  1        |   2        |   0      |
| 4  |  2        |   0        |   0      |
| 5  |  2        |   1        |   1      |
| 6  |  3        |   0        |   0      |

How can I select one row per productId with minimum orderIndex that not rejected? 如何为每个productId选择一行,并且最小orderIndex不被拒绝?

Expected result: 预期结果:

| id | productId | orderIndex | rejected |
------------------------------------------
| 2  |  1        |   1        |   0      |
| 4  |  2        |   0        |   0      |
| 6  |  3        |   0        |   0      |

I tried this query, but don't recieved correct result: 我尝试了这个查询,但没有收到正确的结果:

SELECT id, productId, min(orderIndex)
FROM table
WHERE rejected = 0
GROUP BY productId

This one don't work also: 这个也不起作用:

SELECT id, productId, min(orderIndex)
FROM (
    SELECT id, productId, orderIndex
    FROM table
    WHERE rejected = 0
) t
GROUP BY productId

You can start by selecting the minimum orderIndex of products that are not rejected like this: 您可以从选择未被拒绝的产品的最小orderIndex开始,如下所示:

SELECT productId, MIN(orderIndex)
FROM myTable
WHERE rejected = 0
GROUP BY productId;

Once you have that, you can join it with your original table on the condition that productId and minOrderIndex match: 完成后,您可以在productId和minOrderIndex匹配的条件下将其与原始表连接:

SELECT m.id, m.productId, m.orderIndex
FROM myTable m
JOIN(
  SELECT productId, MIN(orderIndex) AS minOrderIndex
  FROM myTable
  WHERE rejected = 0
  GROUP BY productId) tmp ON tmp.productId = m.productId AND tmp.minOrderIndex = m.orderIndex;

My query makes the assumption that there are no duplicate (productId, orderIndex) pairs. 我的查询假设没有重复(productId,orderIndex)对。 As long as those don't exist, this will work just fine. 只要那些不存在,这将工作得很好。 Here is an SQL Fiddle example. 这是一个SQL小提琴示例。

http://sqlfiddle.com/#!9/0196f/2 http://sqlfiddle.com/#!9/0196f/2

SELECT DISTINCT t.*
FROM table1 t
INNER JOIN (
SELECT productId, min(orderIndex) minIdx
FROM table1
WHERE rejected = 0
GROUP BY productId
  ) t1
ON t.productId = t1.productId
  AND t.orderIndex = t1.minIdx;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM