我正在尝试选择[AssetManager].[AssetType]
的不同选择,其中包含从表[AssetManager].[Asset]
引用资产类型的ID的次数。请参阅下面的示例:
+-----------+-------------+
| Type Name | Asset Count |
+-----------+-------------+
| Phone | 5 |
| Desktop | 12 |
| Laptop | 22 |
+-----------+-------------+
然而,我正在尝试的查询根本不起作用,我得到的最远的是选择具有类型名称的内部联接的资产标题(我在SQL上不是很好......)。请参阅下面的我当前的查询:
SELECT
[Asset].[Title] AssetTitle,
[AssetType].[Title] TypeTitle
FROM
[AssetManager].[Asset]
INNER JOIN
[AssetManager].[AssetType]
ON
[Asset].[AssetType_Id] = [AssetType].[Id]
答案 0 :(得分:2)
正如评论所说,您需要做的就是正确添加GROUP BY
:
SELECT
[AssetType].[Title] TypeTitle
, COUNT(*) [Asset Count]
FROM [AssetManager].[Asset]
INNER JOIN [AssetManager].[AssetType]
ON [Asset].[AssetType_Id] = [AssetType].[Id]
GROUP BY [AssetType].[Title]
答案 1 :(得分:1)
使用OUTER APPLY
从[AssetManager].[Asset]
表
SELECT
DISTINCT [AssetType].[Title] TypeTitle,
M.TypeCount
FROM
[AssetManager].[AssetType]
OUTER APPLY(
SELECT COUNT([Asset].[AssetType_Id]) AS TypeCount
FROM [AssetManager].[Asset]
WHERE [Asset].[AssetType_Id] = [AssetType].[Id]
)M