Imagining I have the following table:
We can see that Tuna was not served in Month 1. I would like to make it appear also in Month 1.
How can I achieve this?
Thank you !
Imagining I have the following table:
We can see that Tuna was not served in Month 1. I would like to make it appear also in Month 1.
How can I achieve this?
Thank you !
You can try to use two subqueries with DISTINCT
and CROSS JOIN
SELECT *
FROM (SELECT DISTINCT Food FROM T) t1
CROSS JOIN (SELECT DISTINCT [Month] FROM T) t2
You can use cross apply
to give each food every month. That seems to be what you want.
declare @table table (Food varchar(16), [Month] int)
insert into @table
values
('Pizza',1),
('Burgers',1),
('Salad',1),
('Tuna',2),
('Pizza',2),
('Burgers',2),
('Salad',2)
select distinct
f.Food
,m.Month
from @table f
cross apply (select distinct [Month] from @table) m
order by m.Month
To find out what months Tuna
was not served in...
select distinct [MONTH]
from @table
where [Month] not in (select [Month] from @table where Food = 'Tuna')
If I understand the issue is that you have a table without the record of the month for some type of food. For me the best way its to create a table "month_of_year" that will contains only the number from 1 to 12.
then:
select distinct Food into #tmp from your_table
select a.Food, month_of_year.month from #tmp a cross join month_of_year
drop table #tmp
then if you want for example see the total of food for the year, go in left from the last table that I have written with the table of the sum, and you will have all the food/month with the total and in case a null on the total where the food was not be served
If you need more information ask =)