2017-01-31 114 views
0

说我有下面的数据集计数重复值的SQL Server 2014

ID| Last | FavColor 
------------------------- 
1 | Johnson | BLUE 
1 | Johnson | RED 
2 | Thomas | YELLOW 
3 | Anderson| BLUE 
3 | Anderson| RED 
3 | Anderson| BLUE 
4 | Phillips| ORANGE 
4 | Phillips| ORANGE 

如何创建一个查询,依旧保持了ID,最后和FavColor,但显示每个颜色的发生次数?

ID| Last | FavColor | Color Count | 
----------------------------------------- 
1 | Johnson | BLUE  |  1  | 
1 | Johnson | RED  |  1  | 
2 | Thomas | YELLOW |  1  | 
3 | Anderson| BLUE  |  2  | 
3 | Anderson| RED  |  1  | 
3 | Anderson| BLUE  |  2  | 
4 | Phillips| ORANGE |  2  | 
4 | Phillips| ORANGE |  2  | 

我试图做一个COUNT(FavColor)PARTITION BY(ID),但不知道如何计算重复。

回答

0

你想通过ID以及分区为favcolor:

SELECT ID, 
    Last , 
    FavColor, 
    COUNT(*) over (partition BY id, favcolor) color_count 
FROM your_table t;