How can it be achieved in MS SQL 2016, when I need to always see every state
under all existing categories
even if there are no records, which satisfy the state
formula?
Under a
and b
below I always want to see all three of later
, earlier
, and same
with null
counts whenever there is no corresponding record.
I guess it should be achievable with some sort of cross join
?..
declare @t table (tid int not null identity(1,1) primary key clustered
,tcat char(1)
,tdat1 date
,tdat2 date
)
insert into @t select * from (values
('a', '2019-01-01', '2019-02-01')
,('a', '2019-02-01', '2019-01-01')
,('b', '2019-02-01', '2019-01-01')
,('b', '2019-01-01', '2019-01-01')
)as t(tcat, tdat1, tdat2)
select
tcat as category
,case
when tdat1 > tdat2 then 'later'
when tdat1 < tdat2 then 'earlier'
when tdat1 = tdat2 then 'same'
end as state
,count(1) as howmany
from @t
group by
tcat
,case
when tdat1 > tdat2 then 'later'
when tdat1 < tdat2 then 'earlier'
when tdat1 = tdat2 then 'same'
end
Best Answer
If I understand your question correctly, here is one way to achieve your goal