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;

SQLフィドル

于 2013-09-06T17:45:26.900 に答える