|
rb1373
Yak Posting Veteran
93 Posts |
Posted - 2005-01-14 : 13:00:44
|
| I am trying to return a single address for each taxid based on the most activity. Most activity is defined as the address with the most checks. If there is a tie in checks, then use total. The problem with the query below is it returns multiple addresses for taxID D. How can I achieve the desired results where there is a single address for taxid D? Thanks. - ray select myid, a.taxid, address, checks, totalfrom mytable ajoin (select TaxID, max(checks) as max_checks from mytable where total > 0 group by TaxID) b on a.TaxID = b.TaxID and a.checks = b.max_checksorder by myidDesired Results:myid taxid address checks total1 A Apple St. 1 10.00003 B Blue St. 2 20.00005 C PO Box 1 2 20.00009 D Dingo St. 1 30.000011 E Emu Pass 1 10.0000CREATE TABLE [dbo].[MyTable] ( [MyID] [int] IDENTITY (1, 1) NOT NULL , [TaxID] [char] (1) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Address] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL , [Checks] [int] NULL , [Total] [money] NULL ) ON [PRIMARY]GOINSERT mytable VALUES('A', 'Apple St.', 1, 10) INSERT mytable VALUES('B', 'Banana St.', 1, 10) INSERT mytable VALUES('B', 'Blue St.', 2, 20) INSERT mytable VALUES('C', 'Car Ave.', 1, 10) INSERT mytable VALUES('C', 'PO Box 1', 2, 20) INSERT mytable VALUES('C', 'Cowboy Way', 1, 50) INSERT mytable VALUES('D', 'Dark Ave.', 1, 10) INSERT mytable VALUES('D', 'Dove Rd.', 1, 20) INSERT mytable VALUES('D', 'Dingo St.', 1, 30) INSERT mytable VALUES('E', 'Elephant Ave.', 2, 0) INSERT mytable VALUES('E', 'Emu Pass', 1, 10) (I haven't attempted to address this issue yet, but if there is a tie between checks and total for a taxid, use the max MyID.) |
|