I\'ve been looking around for a bit and have not been able to find out how to do this yet (though have found alot about analyzing it\'s performance?!)
I want to perform
You're probably better off suppressing duplicates it in the Client (for example in Jasper Reports uncheck Print Repeated Value
or in the XML set isPrintRepeatedValues="false"
)
However on anything that supports WITH
and ROW_NUMBER()
(e.g. Oracle, SQL Server 2005+) .
WITH ns
AS (SELECT Row_number() OVER (PARTITION BY name ORDER BY id) rn,
id,
name,
registered
FROM t
WHERE registered = 'N')
SELECT t.id,
t.name,
ns.id,
ns.name
FROM ns
LEFT JOIN t
ON ns.name = t.name
AND t.registered = 'Y'
AND ns.rn = 1
WHERE ns.name IN (SELECT name
FROM t
WHERE registered = 'Y')
ORDER BY ns.name
See working example
If you don't have WITH and ROW_NUIMBER you can do this
SELECT t.id,
t.name,
ns.id,
ns.name
FROM t ns
LEFT JOIN (SELECT MIN(id) id,
name
FROM t
WHERE registered = 'N'
GROUP BY name) MINNS
ON ns.id = MINNS.id
LEFT JOIN t
ON ns.name = t.name
AND t.registered = 'Y'
AND MINNS.id IS NOT NULL
WHERE ns.registered = 'N'
AND ns.name IN (SELECT name
FROM t
WHERE registered = 'Y')
ORDER BY ns.name,
ns.id
See working example