Subject | RE: [ib-support] COUNT DISTINCT on a composite key |
---|---|
Author | Svein Erling Tysvær |
Post date | 2003-05-03T16:49:48Z |
>{for me} a fascinating puzzle which I don't have time to solve. I startedAn interesting problem that Helen ain't got time to solve! Well, I just got a pretty simple idea, but it requires a bit more than just a query:
>to think about it (actually trying to work out what you needed the count
>for) and, sorry, it's one I can't spare that much time for.
Create a recursive stored procedure along the lines of
CREATE PROCEDURE AllNodes(ANode: Integer)
RETURNS ID INTEGER
AS
DECLARE VARIABLE CurrentNode INTEGER
BEGIN
FOR SELECT ParentID FROM Links WHERE ChildID = :ANode INTO :CurrentNode DO
BEGIN
AllNodes(:CurrentNode);
END
ID = :ANode;
SUSPEND;
END;
Note that I never write stored procedures and haven't even got Firebird on this machine, so the syntax should contain some errors. My thought is that if you call AllNodes(3), that would call AllNodes(2) and AllNodes(1), which in turn would call AllNodes(0) and you would get the following output (well, I haven't thought too much about in which order they would appear):
0
1
0
2
3
Calling SELECT COUNT(DISTINCT ID) FROM AllNodes(3) should then return 4. Since your only interested in the number of parents, you would most likely want to call SELECT COUNT(DISTINCT ID) - 1 FROM AllNodes(3) which should give you 3.
If you get problems with the SP syntax, then I'm sure someone else on this list can help you out.
HTH,
Set
-Fulda is only two weeks away.