2017-01-31 50 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;