Search code examples
sql-server-2005t-sqlcounthierarchysqlxml

TSQL getting record count and records in single query


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>'

Solution

  • select (
              select count(*)
              from Tasks
              where IsDone = 1
              for xml path('CompletedCount'), type
           ),
           (
              select TaskName,
                     case IsDone 
                       when 1 then 'True' 
                       else 'False' 
                     end as IsDone
              from Tasks
              for xml path('Task'), type
           )
    for xml path('Tasks')
    

    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.

    ;with C(Tasks) as
    (
      select TaskName,
             case IsDone 
               when 1 then 'True' 
               else 'False' 
             end as IsDone
      from Tasks
      for xml path('Task'), type
    )
    select C.Tasks.value('count(/Task[IsDone = "True"])', 'int') as CompletedCount,
           C.Tasks
    from C
    for xml path('Tasks')