I'm using SQL server 2012. My table looks like
The different visit types can be - Completed,Bumped,No Show, Late Cancelled and Cancelled. I want to have my output as
Thanks for your help.
I'm using SQL server 2012. My table looks like
The different visit types can be - Completed,Bumped,No Show, Late Cancelled and Cancelled. I want to have my output as
Thanks for your help.
Try the following:
select date,
'Completed: '+sum(case [Visit Type] when 'Completed' then [Count] else 0 end)
+' '+char(10)+'Late Cancelled: '+sum(case [Visit Type] when 'Late Cancelled' then [Count] else 0 end)
+' '+char(10)+'Bumped: '+sum(case [Visit Type] when 'Bumped' then [Count] else 0 end)
+' '+char(10)+'No Show: '+sum(case [Visit Type] when 'No Show' then [Count] else 0 end)
+' '+char(10)+'Cancelled: '+sum(case [Visit Type] when 'Cancelled' then [Count] else 0 end)
as comment
from yourtable
group by date
As already said, not really the way you should be approaching this, grouping of this sort would not be done in SQL.
You can however help things along a bit by grouping the data into XML or JSON if your front end can handle that. Have a look at the following:
DECLARE @myTable AS TABLE (Date DATE
,VisitType NVARCHAR(20)
,Count INT
)
INSERT INTO @myTable
VALUES ('2018-6-3', 'Completed', 9),
('2018-6-3', 'Late Cancelled', 1),
('2018-6-3', 'No Show', 2),
('2018-6-13', 'Completed', 5),
('2018-6-13', 'Bumped', 1),
('2018-6-13', 'No Show', 3)
SELECT Date
, (SELECT VisitType, [Count] FROM @myTable B WHERE B.Date = A.Date FOR XML AUTO ) Result
FROM @myTable A
GROUP BY DATE
You can play with the xml parameters to get the exact format you want. Thats well documented online.