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 Cat开发者_StackOverflow社区egory
However, I also wish to get the Description for each Element. I tried several subqueries, self joins etc., but 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 have run out of ideas as to how to get this done in a single query.
If you need description, you have to include it in the aggregate
SELECT Category ,
[Description] ,
COUNT(*) AS CategoryCount
FROM Tree
WHERE Condition = 'Alpha'
GROUP BY Category ,
[Description]
精彩评论