I am stuck in situation where I am unable to make any progress. The requirement is below.
I have two tables one is ContentTag
Id ContentId TagId
1 48 3
2 48 4
3 48 5
4 48 6
5 47 7
6 47 8
9 47 1
10 47 2
This contains the linking between Content table and tag table
and there is foldettag table which contains the linking between folder table and tag table
Id FolderId TagId
2 2 3
3 2 4
4 2 5
5 2 6
6 4 3
7 5 1
8 5 2
9 5 3
10 10 1
the folder will contain only those contents which are linked to all the tags which are liked to the folder.
Note: I need the result whihc contains the link of those contentId and FolderId which are linked to exactly same tags.
for example it will contain the following result
ContentId FolderId
48 2
Can someone plz suggest to me some approach which I should follow to proceed with this?
I am trying to find a solution for the past few hours but unable to find any solution Thank you
In SQL Server 2017 you can use STRING_AGG()
:
WITH
c AS (
SELECT ContentId, STRING_AGG(TagId, ',') WITHIN GROUP (ORDER BY TagId) tags
FROM ContentTag
GROUP BY ContentId
),
f AS (
SELECT FolderId, STRING_AGG(TagId, ',') WITHIN GROUP (ORDER BY TagId) tags
FROM FolderTag
GROUP BY FolderId
)
SELECT c.ContentId, f.FolderId
FROM c INNER JOIN f
ON f.tags = c.tags
See the demo .
Results:
> ContentId | FolderId
> --------: | -------:
> 48 | 2
If you want a result with the folder and all content that has at least one matching tag, then join
should suffice:
select ft.folderid, ct.contentid
from foldertags ft join
contenttag ct
on ft.tagid = ct.tagid
declare @ContentTag table
(
Id int identity,
ContentId int,
TagId int
);
insert into @ContentTag(ContentId, TagId)
values
(48, 3), (48, 4), (48, 5), (48, 6),
(47, 7), (47, 8), (47, 1), (47, 2),
(46, 4), (46, 6);
declare @FolderTag table
(
Id int identity,
FolderId int,
TagId int
);
insert into @FolderTag(FolderId, TagId)
values
(2, 3), (2, 4), (2, 5), (2, 6),
(4, 3), (5, 1), (5, 2), (5, 3), (10, 1),
(11, 4), (11, 6);
select f.FolderId, c.ContentId
from
(
select FolderId, TagId, count(*) over(partition by FolderId) as FolderTagCount
from @FolderTag
) as f
join
(
select ContentId , TagId, count(*) over(partition by ContentId) as ContentTagCount
from @ContentTag
) as c on f.TagId = c.TagId and f.FolderTagCount = c.ContentTagCount
group by f.FolderId, c.ContentId
having count(f.TagId) = max(c.ContentTagCount);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.