我有一个非常简单的表(用于演示目的)
CREATE TABLE t1 (id int,d1 date);
和这个查询。
SELECT
A.id,
minA,
minB
FROM (SELECT id, MIN(d1) AS minA
FROM t1
GROUP BY id) AS A
LEFT JOIN (SELECT C.id, MIN(C.d1) AS minB
FROM t1 AS C
INNER JOIN (SELECT id, MIN(d1) AS minD
FROM t1
GROUP BY id) AS D ON C.id = D.id AND C.d1 > D.minD
GROUP BY C.id) AS B ON A.id = B.id
基本上,我试图将每个 ID 的两个“最低”日期值排成一行,如果 ID 只有一个日期,则为空值。上面的查询有效,但必须有一种更好/更清洁的方法来做到这一点,而我只是没有看到。如果这很重要,我正在使用 SQL Server 2008。