仅选择数据的最后部分

时间:2013-11-11 13:28:19

标签: sql sql-server

我有以下数据enter image description here

我希望结果如下:

enter image description here

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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'

答案 2 :(得分: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