I need to split my report down to show Food and Alcohol Separate in only one department.
I have Three Separate Departments. 2 Serve Alcohol Only and 1 Serves Alcohol and Food.
Now each department has a different ticket type so that I can see how much each department has taken.
the non food bars item sales are exactly correct as they are only adding up the item group sales for alcohol.
the bar that serves food aswell, the ticket type reports the total sales but I need to pull how much of that was food and how much of that was alcohol.
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE @ColumnName AS NVARCHAR(MAX)
DECLARE @FieldName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @ColumnName= ISNULL(@ColumnName + ',','')
+'FORMAT(ISNULL('+ QUOTENAME(Name) +',0),''0.##;-0.##;-'') as '+Name+''
FROM (SELECT TOP 99 Name FROM Departments order by Name) AS DepartmentNames
SELECT @FieldName= ISNULL(@FieldName + ',','')
+QUOTENAME(Name)
FROM (SELECT TOP 99 Name FROM Departments order by Name) AS DepartmentNames
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'Select MenuItemName,' + @ColumnName + ' from
(select
O.MenuItemName as MenuItemName,
O.Quantity as Quantity,
D.Name as DepartmentName
from Orders as O
inner join Tickets as T on T.Id = O.TicketId
inner join Departments as D on D.Id = T.DepartmentId
where O.DecreaseInventory = 1) as DataTable
PIVOT(
Sum(Quantity)
For DepartmentName
IN (' + @FieldName + ')
) as PivotTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery