Here is the scenario:
I have tables:
-
Articles (articleId, userId, title, datePosted)
-
ArticleTranslations (languageId, articleId, title) (not so important for this case, but I am showing anyway)
-
ArticleSections (articleSectionId, articleId, sectionId)
-
sections (sectionId, content, …)
-
sectionsAdditionalInfo (sectionId, isApproved)
What I am doing is selecting some articles from articles by userId in a way:
SELECT article.articleId, article.userId, ArticleTranslations.title, article.datePosted
FROM Articles
LEFT OUTER JOIN ArticleTranslations ON Article.articleId= ArticlesTranslations.articleId AND ArticlesTranslations.languageId=@languageId
WHERE Articloes.userId=@userId
ORDER BY
CASE WHEN @sortDirection = 'DD' THEN datePosted END DESC, -- by date posted
CASE WHEN @sortDirection = 'DA' THEN datePosted END,
CASE WHEN @sortDirection = 'ND' THEN title END DESC, -- sort by name
CASE WHEN @sortDirection = 'NA' THEN title END,
CASE WHEN @sortDirection = 'SD' THEN ArticleTranslations.isApproved END DESC, -- is article aproved?
CASE WHEN @sortDirection = 'SA' THEN ArticleTranslations.isApproved END,
CASE WHEN @sortDirection = 'ID' THEN areAllSectionsApproved END DESC, -- sort by information if sections are all approved - within the article?
CASE WHEN @sortDirection = 'IA' THEN areAllSectionsApproved END
Please bare in mind I left out some of the info in order for my question to be more understandable.
Now, what I would like to do is select another attribute (for each article returned in SQL above): areAllArticleSectionsApproved
I have assembled SQL separately, but I would like this to be returned for every row:
SELECT CASE WHEN COUNT(sectionsAdditionalInfo.sectionId) > 0 THEN 0 ELSE 1 END AS areAllSectionsApproved
FROM ArticleSections
LEFT OUTER JOIN sectionsAdditionalInfo ON ArticleSections.sectionId = sectionsAdditionalInfo.sectionId
WHERE articleId=@articleId AND sectionsAdditionalInfo.isApproved=0
I have tried nesting this SQL, in a way:
SELECT (outer SQL) .....
a.*(
nested SQL - second one I posted here
) as a
but it didn’t work at all.
I am using SQL server 2008.
Any hint on how to solve this would be greatly appreciated 😉
Without fully understanding your data and your desired results, something like this should work using your above query and joining on your second query as a subquery:
Good luck.