2016-04-07 56 views
0

我想根据另一列中的每个ID来计算不同项目的数量。根据分组条件计算不同的项目

例如

Color  Value 
Red  1 
Red  1 
Red  2 
Red  2 
Blue  3 
Blue  3 

我想要的计数显示红色的有2个不同的价值观和蓝只有1 而摆脱有那些不同值中的较高行的时候重复计数是大于1.在这种情况下,我想摆脱说红色的颜色和2的价值的行。

Color  Value 
Red  1 
Red  1 
Blue  3 
Blue  3 

这里是我真正的查询:在这种情况下FormSectionID将是颜色和myrank将是价值。有没有办法使用这个作为子查询,并得到我想要的?

SELECT DISTINCT TFormSectionID AS FormSectionID, 
    TFSSortOrder AS SectionSortOrder, 
    TSectionItemID AS SectionItemID, 
    TrendType, 
    DENSE_RANK() OVER (ORDER BY TFSSortOrder) AS myrank 
FROM Report.TrendData 
WHERE (ProgramID = 9) AND (TrendType > 0) 

实际数据

FormSectionID SectionSortOrder SectionItemID TrendType Rank 
12     7     90   1    1 
12     7     91   1    1 
12     7     154   1    1 
12     7     528   1    1 
12     9     154   1    2 
12     9     528   1    2 
+0

为什么在您的预期结果中有2行蓝色? – Squirrel

+0

因为对于蓝色的值,不同的计数不会大于1。蓝色的值只包含3. – James

+0

@Squirrel我认为他只是想滤掉颜色组中的任何值,而不是该组中的最小值。 –

回答

1

你可以使用一个聪明INNER JOIN使用子查询:

SELECT c1.Color, c1.Value 
FROM colors c1 
INNER JOIN 
(
    SELECT Color, MIN(VALUE) AS minValue 
    FROM colors 
    GROUP BY Color 
) c2 
    ON c1.Color = c2.Color AND c1.VALUE = c2.minValue 
+0

我会尝试这个 – James

+0

对于c1.Value,它实际上是我的情况下的别名。这是说无效的列名,你知道这个问题的一种解决方法 – James

+0

你犯了一个错误,没有告诉我们你的真实数据。请更新您的问题。 –

0

这是你想要的吗?

declare @tbColor as table (color nvarchar(5),value int) 

insert into @tbColor select 'Red','1' 
insert into @tbColor select 'Red','1' 
insert into @tbColor select 'Red','2' 
insert into @tbColor select 'Red','2' 
insert into @tbColor select 'Red','3' 
insert into @tbColor select 'Blue','3' 
insert into @tbColor select 'Blue','3' 
insert into @tbColor select 'Blue','4' 

select color,value,count(*) as distinctValue from @tbcolor group by color,value