通过电子邮件获得最长post_year组数年

时间:2017-02-19 08:40:24

标签: sql sql-server sql-server-2016

见下表

Email  Post_Year  country
====== ========== =======
a@a.com  2006       US
a@a.com  2007       US
a@a.com  2008       HK1
a@a.com  2008       HK
b@b.com  2009       CN
b@b.com  2010       SW

我想要

  1. 通过电子邮件发送最大Post_year组的所有列,如果有多个最大Post_year,只需选择一个

  2. 以及该特定电子邮件的max(post_year)-min(post_year)的num_of_yrs。

  3. Email  Post_Year  country  Num_Of_Yrs
    ====== ========== ======= =============
    a@a.com  2008      HK       2 [which is 2008-2006]
    b@b.com  2010      SW       1 [which is 2010-2009]
    

    如何达到目的?

2 个答案:

答案 0 :(得分:0)

编辑:根据您编辑的意图,您只需使用:

SELECT 
    email, 
    MAX(post_year) post_year,
    MAX(country) country, 
    MAX(post_year) - MIN(post_year) num_of_yrs
FROM 
    table_name
GROUP BY 
    email;

你可以用这个:

WITH tmp AS
(
    SELECT 
        email, 
        MAX(post_year) max_post_year,
        MIN(post_year) min_post_year
    FROM 
        table_name
    GROUP BY 
        email
)
SELECT 
    t.email,
    t.post_year,
    t.country,
    tmp.max_post_year - tmp.min_post_year num_of_yrs
FROM 
    table_name t
INNER JOIN 
    tmp
ON t.email = tmp.email
    AND t.post_year = tmp.max_post_year;

答案 1 :(得分:0)

您可以使用窗口函数row_number获取一行,每封电子邮件的最大年份和窗口函数max和min,以获得每封电子邮件的最大差异。

试试这个:

select *
from (
    select t.*,
        row_number() over (partition by email 
                            order by post_year desc) rn,
        max(post_year) over (partition by email) -
        min(post_year) over (partition by email) num_of_yrs
    from your_table t
    ) t where rn = 1;