2017-02-25 48 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)