TSQL获取记录计数和单个查询中的记录
我得到了这个包含 TODO 项目的任务表。我们正在单个存储过程中使用单独的查询来检索待办事项和已完成、待处理任务的计数,即使它是从同一个表进行查询。这是查询,
select
TaskName 'Task/TaskName',
CASE IsDone WHEN '1' THEN 'True' ELSE 'False' END 'Task/IsDone',
(
SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
) 'CompletedCount'
FROM Tasks FOR XML PATH('Tasks')
这是输出
'<Tasks>
<Task>
<TaskName>Write a email to Mayor<TaskName>
<IsDone>True</IsDone>
<CompletedCount>2<CompletedCount>
</Task>
</Tasks>'
CompletedCount
存在于每个任务中,这是不必要的,而且无论如何我也可以查询计数,而无需显式编写此 SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
我如何获得如下输出
'<Tasks>
<CompletedCount>2<CompletedCount>
<Task>
<TaskName>Write a email to Mayor<TaskName>
<IsDone>True</IsDone>
</Task>
<Task>
<TaskName>Organize Campaign for website<TaskName>
<IsDone>False</IsDone>
</Task>
</Tasks>'
I got this tasks table that has TODO items. We are retrieving the todo items and the count of Finished, Pending tasks using separate query in single stored procedure even though it is querying from same table. Here is the query,
select
TaskName 'Task/TaskName',
CASE IsDone WHEN '1' THEN 'True' ELSE 'False' END 'Task/IsDone',
(
SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
) 'CompletedCount'
FROM Tasks FOR XML PATH('Tasks')
here is the output
'<Tasks>
<Task>
<TaskName>Write a email to Mayor<TaskName>
<IsDone>True</IsDone>
<CompletedCount>2<CompletedCount>
</Task>
</Tasks>'
CompletedCount
is present in each Task which is unnecessary also is there anyway i can query the count too without explicitly writing this SELECT COUNT(*) FROM Tasks WHERE IsDone = '1'
How do i get a output as below
'<Tasks>
<CompletedCount>2<CompletedCount>
<Task>
<TaskName>Write a email to Mayor<TaskName>
<IsDone>True</IsDone>
</Task>
<Task>
<TaskName>Organize Campaign for website<TaskName>
<IsDone>False</IsDone>
</Task>
</Tasks>'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新:
如果您首先构建任务列表,然后查询 XML 以获取已完成的计数,则可以通过单一选择来完成此操作。我怀疑这会比使用两个 select 语句更快。
Update:
You can do it with a singe select if you first build your task list and then query the XML for the completed count. I doubt this will be any faster than using two select statements.
您可以使用
type
来计算子查询中的 XML 部分:这将打印:
You can use
type
to calculate part of the XML in a subquery:This prints: