使用具有count和group by的别名

时间:2018-06-29 10:15:28

标签: sql-server tsql sql-server-2014

我正在使用SQL Server Management Studio 2014,并且编写了用于计算我正在使用的数据库的每个类别中子类别数量的代码(请参见下文)。

但是,尽管该代码有效,但它会在“无列名”的列中返回结果。

我试图在下面每行的末尾(例如“ FROM”行除外)向代码中添加一个别名,例如as NumberOfSubCats,但这没用!

有人知道如何为未知的列名添加别名吗?

SELECT COUNT(DISTINCT SubCategoryName), CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

2 个答案:

答案 0 :(得分:1)

尝试一下

SELECT COUNT(DISTINCT SubCategoryName) NumberOfSubCats, CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY NumberOfSubCats

答案 1 :(得分:1)

只需在SELECT子句中使用别名:

SELECT COUNT(DISTINCT SubCategoryName) as SubCategoryNameCount, CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

SELECT SubCategoryNameCount = COUNT(DISTINCT SubCategoryName) , CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

SELECT COUNT(DISTINCT SubCategoryName) SubCategoryNameCount, CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

SELECT COUNT(DISTINCT SubCategoryName) 'SubCategoryNameCount', CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

SELECT COUNT(DISTINCT SubCategoryName) [SubCategoryNameCount], CategoryName
FROM v_EnterpriseStructure
GROUP BY CategoryName
ORDER BY COUNT(SubCategoryName); 

以上所有查询的输出为:

enter image description here