我有一个非常简单的表(用于演示目的)
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.
答案 0 :(得分:18)
您可以使用row_number()
获取最早的两个日期,然后使用带有CASE
的聚合函数将数据转移到列中:
select id,
max(case when rn = 1 then d1 end) MinA,
max(case when rn = 2 then d1 end) MinB
from
(
select id,
d1,
row_number() over(partition by id order by d1) rn
from t1
) src
where rn < 3
group by id;
或者您可以使用PIVOT
函数将日期行转换为列:
select id,
[1] MinA,
[2] MinB
from
(
select id,
d1,
row_number() over(partition by id order by d1) rn
from t1
) src
pivot
(
max(d1)
for rn in ([1], [2])
) piv;