2017-02-25 86 views
1

enter image description here獨特的計數通過ID

我會怎麼做一個獨特的計數,這樣對於ID#1計:將綠色 - 2,紅色 - 1,藍色 - 1和ID#2,橙色 - 2,Pink - 1,Blue - 1,White - 1.

然後我需要使用RANK函數按ID排列顏色。我在網上看到如何使用排名功能。

我使用SQL Server 2014

+3

你知道如何使用'rank()',但是你不知道'group by'? –

+0

我已經看到如何使用rank()在線,但我需要通過ID對每種顏色進行唯一計數。我知道如何使用group by,即按id編號 –

+0

SELECT id,將顏色計數(顏色)作爲#D1中的顏色從#Table1中。 –

回答

0

我認爲你正在尋找的查詢的順序:

select id, color, count(*) as cnt, 
     rank() over (partition by id order by count(*) desc) as rnk 
from t 
group by id, color; 
1

您可以通過id,color,然後組的排名依據的計數

select *, rank() over (order by cnt desc) 
from 
    (select *, count(*) as cnt 
    from YourTable 
    group by id, color)