尝试这个:
With Cities
AS (
select Country, City_Code, Min([Date]) Date1, Max([Date]) Date2,
ROW_NUMBER() OVER(PARTITION BY Country ORDER BY Country, City_Code DESC) Seq
from MyCountryCityTable t
group by t.Country, t.City_Code
)
Select
Country,
NULLIF(City_Code,0) City_Code,
CASE WHEN City_Code = 0 THEN NULL ELSE Date1 END Date1,
CASE WHEN City_Code = 0 THEN NULL ELSE Date2 END Date2
From Cities Where Seq = 1
Order by Country
编辑:
没有公用表表达式 ( WITH
) 的版本:
Select
Country,
NULLIF(City_Code,0) City_Code,
CASE WHEN City_Code = 0 THEN NULL ELSE Date1 END Date1,
CASE WHEN City_Code = 0 THEN NULL ELSE Date2 END Date2
From (select Country, City_Code, Min([Date]) Date1, Max([Date]) Date2,
ROW_NUMBER() OVER(PARTITION BY Country ORDER BY Country, City_Code DESC) Seq
from MyCountryCityTable t
group by t.Country, t.City_Code) Cities
Where Seq = 1
Order by Country