I'd use UNPIVOT
for this unless abr
and ubr
are both indexed and a relatively low proportion contain the value 1
.
(Borrowing JNK's table variable)
SELECT id,
Edition
FROM @prod
UNPIVOT (V FOR Edition IN (abr,ubr)) AS Unpvt
WHERE V = 1
How about using with recursive
test view:
create view v as
select *
from ( values ('foo', 2),
('foo', 3),
('foo', 4),
('foo', 10),
('foo', 11),
('foo', 13),
('bar', 1),
('bar', 2),
('bar', 3)
) as baz ("name", "int");
query:
with recursive t("name", "int") as ( select "name", "int", 1 as span from v
union all
select "name", v."int", t.span+1 as span
from v join t using ("name")
where v."int"=t."int"+1 )
select "name", "start", "start"+span-1 as "end", span
from( select "name", ("int"-span+1) as "start", max(span) as span
from ( select "name", "int", max(span) as span
from t
group by "name", "int" ) z
group by "name", ("int"-span+1) ) z;
result:
name | start | end | span
------+-------+-----+------
foo | 2 | 4 | 3
foo | 13 | 13 | 1
bar | 1 | 3 | 3
foo | 10 | 11 | 2
(4 rows)
I'd be interested to know how that performs on your billion row table.
Best Answer
It's not entirely clear what you're trying to accomplish but I think you basically want only the
Computer_ids
of the rows that haveSofrware
of7Zip
or theComputer_ids
of the rows that don't haveSoftware
of7Zip
in any other row for that sameComputer_id
, and you want the value to beno
. You can accomplish this with aUNION ALL
clause and an outer self-join like so:If you have the same
Computer_id
more than once in either case and you only want one row for it, you can add theDISTINCT
clause to yourSELECT
clause in each query of theUNION ALL
above too.