SQL - 结果部分基于特定列的聚合

时间:2017-07-10 20:28:58

标签: sql sql-server

提前感谢您的任何帮助。我有一种情况需要SQL数据的快照,但部分结果需要基于一列的聚合。这是我数据的一小部分:

| A | B | last_date  | next_date  | C | D |
| 1 | 3 | 01/01/2000 | 01/01/2003 | 1 | 1 |
| 1 | 3 | 01/01/2001 | 01/01/2004 | 1 | 2 |
| 2 | 3 | 01/01/2002 | 01/01/2005 | 2 | 3 |
| 2 | 4 | 01/01/2003 | 01/01/2006 | 3 | 4 |

我的结果需要按A列和B列,last_date的MAX和下一个日期的MIN进行分组。但是,踢球者是C列和D列的值应该是与下一个日期的MIN相对应的值。因此,对于上述数据子集,我的结果将是:

| A | B | last_date  | next_date  | C | D |
| 1 | 3 | 01/01/2001 | 01/01/2003 | 1 | 1 |
| 2 | 3 | 01/01/2002 | 01/01/2005 | 2 | 3 |
| 2 | 4 | 01/01/2003 | 01/01/2006 | 3 | 4 |

注意第一行结果如何具有初始数据第2行的last_date值,但列C和D的值对应于初始数据的第一行。如果A,B,max(last_date)和min(next_date)列完全重复,但C列和D列的值不匹配,那我就不在乎哪一个返回 - 但我必须只返回一行,而不是多次。

1 个答案:

答案 0 :(得分:1)

您可以使用row_number adn获取此结果,如下所示:

Select A, B, MaxLast_date, MinNext_date, C, D from (
    select *, max(last_date) over(partition by A, B) as MaxLast_date, Min(next_date) over(partition by A, B) as MinNext_date,
        next_rn = Row_number() over(partition by A, B order by next_date)   from #yourtable
) a 
Where a.next_rn = 1

其他方式是top(1)带有如下关系:

Select top(1) with ties *, max(last_date) over(partition by A, B) as MaxLast_date, Min(next_date) over(partition by A, B) as MinNext_date
    from #yourtable
    Order by Row_number() over(partition by A, B order by next_date)    

输出:

+---+---+--------------+--------------+---+---+
| A | B | MaxLast_date | MinNext_date | C | D |
+---+---+--------------+--------------+---+---+
| 1 | 3 | 2001-01-01   | 2003-01-01   | 1 | 1 |
| 2 | 3 | 2002-01-01   | 2005-01-01   | 2 | 3 |
| 2 | 4 | 2003-01-01   | 2006-01-01   | 3 | 4 |
+---+---+--------------+--------------+---+---+

Demo