T-SQL Self Join in combination with aggregate function
        Posted  
        
            by Nick
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Nick
        
        
        
        Published on 2010-05-18T18:53:25Z
        Indexed on 
            2010/05/18
            19:00 UTC
        
        
        Read the original article
        Hit count: 214
        
tsql
Hi,
i have the following table.
CREATE TABLE [dbo].[Tree](
 [AutoID] [int] IDENTITY(1,1) NOT NULL,
 [Category] [varchar](10) NULL,
 [Condition] [varchar](10) NULL,
 [Description] [varchar](50) NULL,
 CONSTRAINT [PK_Tree] PRIMARY KEY CLUSTERED 
(
 [AutoID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
the data looks like this:
INSERT INTO [Test].[dbo].[Tree]
           ([Category]
           ,[Condition]
           ,[Description])
     VALUES ('1','Alpha','Type 1')
INSERT INTO [Test].[dbo].[Tree]
           ([Category]
           ,[Condition]
           ,[Description])
     VALUES ('1','Alpha','Type 1')
INSERT INTO [Test].[dbo].[Tree]
           ([Category]
           ,[Condition]
           ,[Description])
     VALUES ('2','Alpha','Type 2')
INSERT INTO [Test].[dbo].[Tree]
           ([Category]
           ,[Condition]
           ,[Description])
     VALUES ('2','Alpha','Type 2')
go
I try now to do the following:
SELECT Category,COUNT(*) as CategoryCount FROM Tree where Condition = 'Alpha' group by Category
but i wish also to get the Description for each Element. I tried several subqueries, self joins etc. i always come to the problem that the subquery cannot return more than one record.
The problem is caused by a poor database design which i cannot change and i run out of ideas to get this done in a single query ;-(
© Stack Overflow or respective owner