I have a simple table :
DECLARE @t TABLE(item INT, itemType INT )
insert INTO @t SELECT 1000,0
insert INTO @t SELECT 1000,3
insert INTO @t SELECT 1000,5
insert INTO @t SELECT 1000,6
insert INTO @t SELECT 2000,0
insert INTO @t SELECT 2000,3
insert INTO @t SELECT 2000,5
insert INTO @t SELECT 2000,6
insert INTO @t SELECT 3000,0
insert INTO @t SELECT 3000,10
insert INTO @t SELECT 4000,11
I want to select all items where itemtype = 3 but if there is a row , provide also its base itemtype (if it exists) which is itemType = 0.
For example :
-
for itemType = 3
1000,0should be provided –why ? because table also has 1000 + itemType 0
1000,3should be provided –why ? because we looked for itemType=3
2000,0should be provided –why ? because table has found 2000,3 and this 2000 also has itemType=0
2000,3should be provided –why ? because we looked for itemType=3 -
for itemType = 10
3000,0should be provided –why ? because table has found 3000,10 and this 3000 also has itemType=0
3000,10should be provided –why ? because we looked for itemType=10 -
for itemType = 11
4000,11should be provided –why ? because we looked for itemType=11 ( notice , there isn’t itemType 0 , so only itself).
I started doing :
;with cte as(
SELECT * FROM @t
)
select * from cte where itemType=3
In summary, if the itemType is found, provide itself + its zero type (if exists), and also for his siblings ( sample(#1) )
But I can’t do rubbish. it is possible.union here cause CTE is not recognized there…
How can I solve it ?
To avoid evaluating the
itemType = 3query twice you can self outer join then useCROSS APPLY ... VALUEStoUNPIVOTSQL Fiddle
Execution Plans