根据所见,像这样的通用 SQL 查询会将这些行“扁平化”为单行(但 2 PgsCompleted 值需要不同的列名)。
select
AutoArtId
, empArtStage
, MIN(ArtStageCurrStat) as ArtStageCurrStat
, MIN(PgsCompleted) as PgsCompleted1
, MAX(PgsCompleted) as PgsCompleted2
from YourTable
group by AutoArtId, empArtStage
出现一些关于多于或少于 2 行的问题,这可能会有所帮助:
select
AutoArtId
, empArtStage
, MIN(ArtStageCurrStat) as ArtStageCurrStat
, MIN(PgsCompleted) as PgsCompleted1
, MAX(PgsCompleted) as PgsCompleted2
, count(*) as num_of
from YourTable
group by AutoArtId, empArtStage
having count(*) <> 2
这是一种使用 SQL 2008 中可用的 row_number() 的方法。它假设您在表中有一些字段可以区分最旧和最新(这里我使用了自动编号的 ID) - 并且假设最旧和最新的是相关记录对。在这个 sqlfiddle 中,我模拟了一些样本数据,代表一组 3 条记录和另一条记录。
SELECT
AutoArtId
, empArtStage
, MIN(ArtStageCurrStat) AS ArtStageCurrStat
, MIN(PgsCompleted) AS PgsCompleted1
, MAX(PgsCompleted) AS PgsCompleted2
FROM (
SELECT
AutoArtId
, empArtStage
, ArtStageCurrStat
, PgsCompleted
, row_number() over (partition BY AutoArtId, empArtStage
ORDER BY ID ASC) AS oldest
, row_number() over (partition BY AutoArtId, empArtStage
ORDER BY ID DESC) AS newest
FROM YourTable
) AS derived
WHERE oldest = 1 OR newest = 1
GROUP BY
AutoArtId
, empArtStage