0

我错过了一层我认为不相关的复杂性,但似乎就是这样,因为 MIN() 建议似乎不适用于此。

我有一个看起来像的表:

col-1 | col-b | col-c | col-d
----------------------------------
mhm1  | a     | 09:20 | 2013-09-21
mhm1  | b     | 09:21 | 2013-09-20
mhm1  | c     | 09:22 | 2013-09-19
mhm1  | c     | 09:23 | 2013-09-18
mhm1  | d     | 09:24 | 2013-09-19
mhm2  | a     | 09:25 | 2013-09-21
mhm2  | c     | 09:26 | 2013-09-20
mhm2  | d     | 09:27 | 2013-09-19
mhm2  | c     | 09:28 | 2013-09-18

我想要一个查询,它返回每个唯一 col-1 的第一行,其中 col-b = 'c'。

例如

col-1 | col-b | col-c | col-d
---------------------------------
mhm1  | c     | 09:23 | 2013-09-18
mhm2  | c     | 09:28 | 2013-09-18

实现此目的的适当 SQL 请求是什么?我努力了:

SELECT col-a, col-b, min(col-c), min(col-d) FROM MY TABLE
WHERE col-b = 'c'
GROUP BY col-a
ORDER BY col-c ASC

但我得到:

col-1 | col-b | col-c | col-d
---------------------------------
mhm1  | c     | 09:22 | 2013-09-18
mhm2  | c     | 09:26 | 2013-09-18

这不是我想要的。

谢谢

4

3 回答 3

0
DROP TABLE IF EXISTS my_test;

CREATE TABLE my_test (col1 CHAR(4) NOT NULL,colb CHAR(1) NOT NULL,colc TIME NOT NULL,PRIMARY KEY(col1,colb,colc));

INSERT INTO my_test VALUES
('mhm1','a','09:20:00'),
('mhm1','b','09:21:00'),
('mhm1','c','09:22:00'),
('mhm1','c','09:23:00'),
('mhm1','d','09:24:00'),
('mhm2','a','09:25:00'),
('mhm2','c','09:26:00'),
('mhm2','d','09:27:00'),
('mhm2','c','09:28:00');

SELECT x.* 
  FROM my_test x 
  JOIN 
     ( SELECT col1,colb,MIN(colc) min_colc FROM my_test GROUP BY col1,colb) y 
    ON y.col1 = x.col1 
   AND y.colb=x.colb 
   AND y.min_colc = x.colc 
WHERE x.colb = 'c';
+------+------+----------+
| col1 | colb | colc     |
+------+------+----------+
| mhm1 | c    | 09:22:00 |
| mhm2 | c    | 09:26:00 |
+------+------+----------+
于 2013-06-06T13:49:19.040 回答
0

使用MIN() 函数告诉 MySQL,您想要该组中的最低值。

SELECT col-a, col-b, MIN(col-c) FROM MY_TABLE
WHERE col-b = 'c'
GROUP BY col-a
/* ORDER BY col-c ASC <-- this is not necessary*/

这将在您的示例中起作用。但这可能很危险。其他列值不需要属于具有最小 col-c 值的行。为此,您必须按如下方式编写:

SELECT col-a, col-b, col-c FROM MY_TABLE t
WHERE col-b = 'c'
AND col-c = (SELECT MIN(col-c) FROM yourTable yt WHERE yt.col-a = t.col-a)
GROUP BY col-a

有关更多示例,请参阅此手册条目

于 2013-06-06T13:43:34.123 回答
0

我认为您可以使用MIN()函数来 col-c 来实现这一点

SELECT col-1, col-b, MIN(col-c)
FROM MY TABLE
WHERE col-b = 'c'
GROUP BY col-1
ORDER BY col-c ASC

现场 SQLFiddle

于 2013-06-06T13:43:47.360 回答