By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,287 Members | 1,287 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,287 IT Pros & Developers. It's quick & easy.

SQL how to

P: n/a
I have two tables :
CREATE TABLE animals
(
BHID BIGINT NOT NULL,
CONTROLLER INTEGER NOT NULL,
LOCATION INTEGER NOT NULL,
....
)
CREATE UNIQUE INDEX PRIMARY_A ON ANIMALS(BHID);

ALTER TABLE animals
ADD CONSTRAINT PRIMARY PRIMARY KEY
(BHID);
CREATE TABLE owners
(
bhid BIGINT NOT NULL,
entity_id INTEGER NOT NULL,
starting DATE NOT NULL,
percent DECIMAL(7, 4) NOT NULL DEFAULT 100,
ending DATE
)
DATA CAPTURE NONE;

CREATE UNIQUE INDEX primary_o ON owners(bhid, entity_id, starting);

ALTER TABLE owners
ADD CONSTRAINT primary PRIMARY KEY
(bhid, entity_id, starting);

I want a table with a single row for each animal along with one owner,
independent of the number of owners, 0, 1, or more. In the case that
more than one owner for a particular animal exists I would like the
owner with the largest percentage, if there is one. When the percentages
are equal (50/50., etc.), any of the owners will do. If there was not
the requirement that there only be one row per animal a LEFT OUTER JOIN
ON animals.bhid=owners.bhid would suffice.

I am at a loss as how to do this without a table returning function,
which I am loathe to write because of the performance hit.

Nov 12 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
Ian
Robert Stearns wrote:
I want a table with a single row for each animal along with one owner,
independent of the number of owners, 0, 1, or more. In the case that
more than one owner for a particular animal exists I would like the
owner with the largest percentage, if there is one. When the percentages
are equal (50/50., etc.), any of the owners will do. If there was not
the requirement that there only be one row per animal a LEFT OUTER JOIN
ON animals.bhid=owners.bhid would suffice.


Can you do something like:

select
bhid
,location
,entity_id
,percent
from (
select
a.bhid
,a.location
,o.entity_id
,o.percent
,rownumber() over (partition by o.bhid
order by o.percent desc) as owner_rank
from
animals a
left outer join owners o
on a.bhid=o.bhid
) as x
where
owner_rank = 1;


-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----
Nov 12 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.