Relationship of SQL queries to product tag
I have a database for an e-commerce store. MSSQL 2008.
I have a table called Products and a table called Tags. This is a many-to-many relationship linked together by the ProductTags table.
Products:
id, name, price
Tags:
id, name, sortorder, parentid (allow null)
ProductTags:
productid, tagid
I'm trying to create a view in SQL, but I just completely suck at writing SQL.
The view should consist of:
Tags.id, Tags.Name, Tags.sortorder, Tags .parentid, ProductCount, ChildTagCount
ProductCount is the number of products associated with this tag. ChildTagCount is the number of tags for which this tag ID is its parent.
+1
source to share
3 answers
SELECT Tags.ID, Tags.Name, Tags.SortOrder, Tags.ParentID,
COUNT(DISTINCT ProductTags.ProductID) AS ProductCount,
COUNT(DISTINCT ChildTags.ID) AS ChildTagCount
FROM Tags
LEFT OUTER JOIN ProductTags ON Tags.ID = ProductTags.TagID
LEFT OUTER JOIN Tags ChildTags ON Tags.ID = ChildTags.ParentID
GROUP BY Tags.ID, Tags.Name, Tags.SortOrder, Tags.ParentID
+2
source to share