I have a temp table that stores rollup data and would like to create a query to see if I could clean up the data a little bit. I thought it would be pretty easy but it has turned out to be much more difficult. Maybe it is easy and I’m just approaching it all wrong.
What I’m trying to do is simply remove rows where Item = ‘TOTALS’ but where a name only shows up twice. So in the table below, rows 7 and 9 should be removed. Just so you know, there are no keys.
Name . Item ……Dlvrd
————————–
Bob . 102 ………. 18
Bob . 106 ………. 32
Bob . 108 ………. 34
Bob . 999 ………. 184
Bob .. TOTALS . 702
John . 64 ……….. 86
John . TOTALS . 86
Jim .. 112 ………. 131
Jim .. TOTALS .. 131
Jane . 10 ………. 720
Jane . 12 …….. . 217
Jane . 999 …….. 867
Jane . TOTALS 1848
My first attempt consisted of adding a column with the count of the name column, then using a where clause like: where name != ‘2’ and Item != ‘TOTALS’. Didn’t work, even putting parenthesis around them. It just removes any row with a 2 or where Item = ‘TOTALS’. It’s totally ignoring the ‘AND’. Here my sql:
select t.count, tr.*
From #TempRollup tr
join (
select
Name
, COUNT(Name) count
from #TempRollup
Group by Name
) as t on t.Name = tr.Name
where (
t.count != 2
and Item != 'TOTALS'
)
Then I tried this method that involves creating a subquery to find the rows I want to ignore and then just not selecting them. My subquery grabs the correct rows but when the whole thing is run, nothing is returned.:
Select *
FROM #TempRollup
WHERE NOT EXISTS(
select tr.*
From #TempRollup tr
join (
select
Name
, COUNT(Name) count
from #TempRollup
Group by Name
) as t on t.Name = tr.Name
where t.count = 2
and Item = 'TOTALS'
)
Try this:
SQL Fiddle example