[英]SQL Server: How to add count to nested select
I have two tables, one containing a list of files and one containing a list of tags which are linked by a fileID. 我有两个表,一个包含文件列表,另一个包含由fileID链接的标签列表。
Currently I select this as follows which works fine so far. 目前我选择如下,到目前为止工作正常。
How do I have to amend this if I want to count the tags per file and show this in addition to the selected data ? 如果我想计算每个文件的标签并显示除了所选数据之外的其他信息,我该如何修改? What I want to do is show how many tags are assigned to each file.
我想要做的是显示为每个文件分配了多少标签。
My SP: 我的SP:
SELECT C.fileTitle,
C.fileID,
(
SELECT T.fileTag
FROM Files_Tags T
WHERE T.fileID = C.fileID
ORDER BY T.fileTag
FOR XML PATH(''), ELEMENTS, TYPE
) AS tags
FROM Files C
ORDER BY C.fileTitle
FOR XML PATH('files'), ELEMENTS, TYPE, ROOT('root')
Many thanks for any help with this, Tim. 蒂姆,非常感谢你提供的任何帮助。
You can add a subquery: 您可以添加子查询:
SELECT C.fileTitle,
C.fileID,
(
SELECT COUNT(*)
FROM Files_Tags T
WHERE T.fileID = C.fileID
) AS NumTags,
(
SELECT T.fileTag
FROM Files_Tags T
WHERE T.fileID = C.fileID
ORDER BY T.fileTag
FOR XML PATH(''), ELEMENTS, TYPE
) AS tags
You could also put in a join
and aggregation in the outer query. 您还可以在外部查询中添加
join
和聚合。 But, your query already has to use a nested select for the concatenation, so you might as well use the same structure for the count. 但是,您的查询必须使用嵌套选择进行连接,因此您也可以使用相同的计数结构。
Can't you just do this?: 你不能这样做吗?:
SELECT C.fileTitle,
C.fileID,
(
SELECT T.fileTag
FROM Files_Tags T
WHERE T.fileID = C.fileID
ORDER BY T.fileTag
FOR XML PATH(''), ELEMENTS, TYPE
) AS tags,
(
SELECT
COUNT(*)
FROM
Files_Tags T
WHERE
T.fileID = C.fileID
) AS NumberOfTages
FROM Files C
ORDER BY C.fileTitle
FOR XML PATH('files'), ELEMENTS, TYPE, ROOT('root')
Anding a sub query for the count 和计数的子查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.