Jump to content

this is quite a challenge but any help is appreciated


linkin

Recommended Posts

ok basicly I have a table, which contain three columns:

ID | ID2 | ID3
--------------
1    5        6
2    3        8
3    3        7
4    3        9
5    25      18
--------------

the inputs will be ID3 (e.g. 7,9,18) i.e multiple inputs, not just one
the output needs to be: which is the most popular ID2, based on how many ID3 shared. sorted by popularity.
e.g. input of 7,9,8,18 will result in 3 and then 25

all i need is the SQL query, if you can help i would appreciate it
if you need more explanation, tell me.
thanks in advance
Link to comment
Share on other sites

If I understand you correctly, then a query like this will get you the result you want:

SELECT
  id2
, COUNT(id2) AS id2_count
FROM
ids_table
WHERE
id3 IN (7, 9, 8, 18)
GROUP BY
id2
ORDER BY
id2_count DESC  # most popular first
;

Outputs something like:

id2  id2_count
---  ----------
3          3
25        1


When you want to only select the most popular that have at least 2 or more entries, then use the HAVING clause, as in this example:

SELECT
  id2
, COUNT(id2) AS id2_count
FROM
ids_table
WHERE
id3 IN (7, 9, 8, 18)
GROUP BY
id2
HAVING
id2_count > 1    # At least 2 or more hits
ORDER BY
id2_count DESC  # most popular first
;

Which would only return:

id2  id2_count
---  ----------
3          3

Notice it would not return the 25 in this example.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.