2

I've been looking around and can't find an answer to this question on finding a distinct match. I have a table that looks like

ID       Category     Relevancy
192820  273003000   2
242567  273003000   2
510711  273003000   2
510711  273003002   34
542178  273003000   1
542178  273003002   2
688833  273003000   3
734917  273003002   2
888879  273003000   1
891624  273003002   3

So for each id they can have multiple categories and the relevancy is what what category number (1 is the first category, 2 second, 34 the thirty fourth category for that id).

I want to query where I can search the count of the Category but if the id has already been counted for a category it will not be counted.

So for this the answer would look like:

Category         Count  
273003000         6
273003002         2

Thanks for the help!!

4

2 回答 2

3

听起来您只想计算Relevancy每个记录的最小值ID。因此,您可以这样做(SQL Fiddle 示例):

SELECT Category, COUNT(1)
FROM Table1 t1
WHERE NOT EXISTS
(
    SELECT 1
    FROM Table1 t2
    WHERE t2.ID = t1.ID
    AND t2.Relevancy < t1.Relevancy
)
GROUP BY Category
于 2013-09-06T17:41:45.980 回答
0

这应该可以解决问题,因为您不关心 Relevancy 值本身,而只关心计数:

select a.category, count(a.relevancy) as count
from (select *
      from test
      group by id) as a
group by a.category;

SQLFiddle

于 2013-09-06T17:45:26.900 回答