1

我有以下数据在此处输入图像描述

我希望结果是这样的:

在此处输入图像描述

对于阿尔巴尼亚,我想为阿尔巴尼亚的 City_Code 的最后一个值(此处为 20008)选择日期的最小值和最大值(20008 的最小值为 18.01.2013,20008 的最大值为 20.01.2013) . 对于克罗地亚,City_Code 的最后一个值是“零”,所以我们不应该选择任何东西(如果“City_Code”的最后一个值为零,则根本不要选择它)。对于斯洛文尼亚,City_Code 的最后一个值为 70005,因此我们选择对应日期的最小值和最大值(此处最大值和最小值为 22.01.2013)。代码应该是什么样子?我没有任何想法。提前致谢

4

3 回答 3

1
SELECT Country,
       max(City_code),
       min(DATE),
       max(Date)
FROM T as T1
WHERE City_code = (SELECT TOP 1 City_Code 
                          FROM T WHERE T.Country=T1.Country 
                          ORDER BY Date DESC)
GROUP BY Country
HAVING max(City_Code)<>'0'
于 2013-11-11T13:51:50.973 回答
1

尝试这个...

;
WITH    cte_countries ( Country, City_code, CurrentDate, LatestRank )
          AS ( SELECT   Country ,
                        City_code ,
                        CurrentDate ,
                        RANK() OVER ( PARTITION BY country ORDER BY CurrentDate DESC ) AS LatestRank
               FROM     @countries
               WHERE City_code != 0
             )
    SELECT  *
    FROM    cte_countries
    WHERE   LatestRank = 1
于 2013-11-11T13:44:24.070 回答
0

尝试这个:

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
于 2013-11-11T13:50:37.343 回答