按列中的唯一值计数

时间:2014-06-04 10:11:15

标签: mysql sql

我有一个类似于(parent, child, item, frequency)

的架构

同一个父母可以有多个孩子,不同孩子可以有重复频率的重复项目。 e.g。

PA    CA   IA  FA
PA    CB   IA  FA
PA    CB   IB  FB

请注意,CA和CB都有一个共同的项目。

所以,现在我想要所有不同的父母以及频率之和。例如对于上表,答案是PA,(FA + FB)。 (注意:不是2 * FA + FB)。

我尝试使用以下SQL查询,但这给了我2 * FA + FB。

SELECT distinct [parent], sum(frequency) as freq
FROM [sampleDB].[dbo].[sampleTable]
group by [parent]
order by freq DESC

这是有道理的,因为不同于父,而不是查询。注意到这个错误,然后我尝试了

SELECT distinct [parent], sum(frequency from (Select distinct [item], [frequency])) as freq
FROM [sampleDB].[dbo].[sampleTable]
group by [parent]
order by freq DESC

但这会产生语法错误。什么应该是正确的查询?

3 个答案:

答案 0 :(得分:1)

可能你需要这个:

SELECT parent, SUM(frequency) AS freq
FROM (SELECT DISTINCT parent, item, frequency FROM sampleTable) AS t 
GROUP BY parent
ORDER BY freq DESC

答案 1 :(得分:0)

试试这个:

SELECT parent, sum(frequency) FROM (SELECT DISTINCT parent, frequency FROM table_name) GROUP BY parent

答案 2 :(得分:0)

如果我理解正确,你想先在父级/项目级别进行总结,然后对频率求和:

select parent, sum(frequency)
from (select distinct parent, item, frequency
      from sampletable st
     ) st
group by parent;