K
K
KTG2018-11-07 10:18:24
Oracle
KTG, 2018-11-07 10:18:24

How to correctly build a query to two tables?

There are 2 tables:
first:
UserID - Cat - Group
1200 - 1 - 3
1200 - 4 - 20
1200 - 2 - 7
1235 - 1 - 2
1235 - 4 - 20
1450 - 1 - 3
second:
UserID - UserName
1200 - Ivan
1235 - Peter
1450 - Dima It is
necessary to create a query that will return the username of the user included in all specified Category-Group pairs.
At the moment I'm using the following structure:

SELECT
   COUNT(UserID)
 , UserName
FROM usertable ut
 INNER JOIN catgrouptable cg ON ut.UserID = cg.UserID
                                              AND (
                                                                (cg.cat = 1 AND cg.group IN (3,10,9))
                                                          OR (cg.cat = 4 AND cg.group IN (1,2,3,20))
                                                         --  неопределенное количество условий вхождения в группы и категории
                                                       )
GROUP BY UsetName
HAVING COUNT(UserID)

Each OR - gives me an entry into one of the groups according to the corresponding category
Through COUNT, I consider the fulfillment of the condition for one of the pairs.
HAVING leaves only those records that have passed all conditions.
But I'm always confused by the use of the HAVING construct. Therefore, the question is whether there is a more elegant solution, which would also eliminate the error when the user has more than one group in the category.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
idShura, 2018-11-07
@idShura

So?

select t2.UserName
 from TAB1 t1 
      left join TAB2 t2 on t2.UserID = t1.UserID
where (t1.cat = 1 AND t1.group IN (3,10,9))
   OR (t1.cat = 4 AND t1.group IN (1,2,3,20))
   --  неопределенное количество условий вхождения в группы и категории
group by t2.UserName

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question