SQL WHERE临时列

时间:2015-12-01 20:49:51

标签: sql sql-server sql-server-2008

我有这个MSSQL查询工作

SELECT c.CategoryName + ' (' + cast(count(ic.CategoryId) as varchar(255)) + ')' AS
 CategoryName, count(ic.CategoryId) AS NumPhotos,
  c.Slug, c.ParentCategoryId, c.Id
FROM Categories
 c LEFT JOIN
 ItemCategories ic
 on ic.CategoryId = c.Id
GROUP BY c.CategoryName, c.slug, c.ParentCategoryId, c.id
ORDER BY ParentCategoryId DESC

我想只返回行,WHERE NumPhotos> 0但SQL WHERE子句不允许使用临时列

2 个答案:

答案 0 :(得分:2)

having子句是您问题的规范解决方案。但是,我怀疑inner join也是合适的:

SELECT c.CategoryName + ' (' + cast(count(ic.CategoryId) as varchar(255)) + ')' AS CategoryName,
       count(ic.CategoryId) AS NumPhotos,
       c.Slug, c.ParentCategoryId, c.Id
FROM Categories c INNER JOIN
     ItemCategories ic
     on ic.CategoryId = c.Id
GROUP BY c.CategoryName, c.slug, c.ParentCategoryId, c.id
ORDER BY ParentCategoryId DESC;

没有样本数据,很难确定,但我很确定这会做同样的事情。

inner join的优势在于它可能更有效,因为处理的数据更少(可能只是略少),优化器有更多机会选择最佳join算法。 / p>

答案 1 :(得分:1)

现有评论给出了足够的答案,但这是另一种解决方案,使用"虚拟表":

SELECT * FROM ( 
SELECT c.CategoryName + ' (' + cast(count(ic.CategoryId) as varchar(255)) + ')' AS
 CategoryName, count(ic.CategoryId) AS NumPhotos,
  c.Slug, c.ParentCategoryId, c.Id
FROM Categories
 c LEFT JOIN
 ItemCategories ic
 on ic.CategoryId = c.Id
GROUP BY c.CategoryName, c.slug, c.ParentCategoryId, c.id
) 
WHERE NumPhotos>0
ORDER BY ParentCategoryId DESC