-3

I am looking for similar records in the same table. I tried IN clause (below query) but it is not working as per the expectation.

Select * from tblBlogCategory Where CategoryID IN (Select CategoryID from tblBlogCategory Where BlogID=1)

i.e. I have BlogID=1. I want those records in the table whose CategoryID is 1 and 2 both. It is also fine if any new CategoryID 3 is there. So, for the below table, It should return BlogID 3.

How do I achieve this?

enter image description here

Expected Output:
enter image description here

Jeeten Parmar
  • 5,568
  • 15
  • 62
  • 111

3 Answers3

1

Try this:

Table Schema:

CREATE TABLE YourTable(BlogId INT, CategoryId INT)

INSERT INTO YourTable VALUES(1,1)
INSERT INTO YourTable VALUES(1,2)
INSERT INTO YourTable VALUES(2,1)
INSERT INTO YourTable VALUES(3,1)
INSERT INTO YourTable VALUES(3,2)
INSERT INTO YourTable VALUES(3,3)

Query:

DECLARE @BlogID INT = 1

SELECT * 
FROM YourTable  
WHERE BlogID IN(
    SELECT A.BlogID 
    FROM YourTable A
    JOIN (
        SELECT CategoryId
        FROM YourTable
        WHERE BlogID = @BlogID
    )B ON A.CategoryId = B.CategoryId
    GROUP BY A.BlogID
    HAVING COUNT(DISTINCT A.CategoryId)>=(SELECT COUNT(DISTINCT CategoryId) FROM YourTable WHERE BlogID = @BlogID)
  )
AND BlogID != @BlogID

Output:

| BlogId | CategoryId |
|--------|------------|
|      3 |          1 |
|      3 |          2 |
|      3 |          3 |

SQL Fiddle Link

DineshDB
  • 5,998
  • 7
  • 33
  • 49
0

If I got you correctly, You could use

select * from tblBlogCategory where BlogID=1

you should get all CategoryID where BlogID=1 which you may also further filter

 select * from tblBlogCategory where BlogID=1 and CategoryID in (1,2)
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
Gnyasha
  • 658
  • 11
  • 19
0

If you just want to return blog ids that have matches, then this should be sufficient:

select bc.blogid
from tblBlogCategory bc join
     tblBlogCategory bc1
     on bc1.categoryid = bc.categoryid and
        bc1.blogid = 1 and
        bc1.blogid <> bc.blogid
group by bc.blogid
having count(*) = (select count(*) from tblBlogCategory bc where bc.blogid = 1);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786