Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Count multiple items in same column

Author  Topic 

KidCactus
Starting Member

3 Posts

Posted - 2013-01-17 : 12:30:32
I'll go straight to my dilemma. I have a table with a column that looks something like this:

column1

dog,id1
cat,id1
cat,id3
dog,id1
dog,id2
cat,id3
cat,id1
dog,id2
cat,id2
dog,id3


I would like to do a query that would give this result in three columns:

column1    cat    dog

id1 2 2
id2 1 2
id3 2 1


I don't even know where to start, but I assume this shouldn't be that hard to obtain?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-01-17 : 13:01:43
This, if you have just cats and dogs. But if you have hamsters and goldfish and all other kinds of exotic pets, you would need to use some kind of dynamic query perhaps, especially if the kinds of pets are unknown in advance
CREATE TABLE #data(column1 VARCHAR(32));
INSERT INTO #data VALUES
('dog,id1'),
('cat,id1'),
('cat,id3'),
('dog,id1'),
('dog,id2'),
('cat,id3'),
('cat,id1'),
('dog,id2'),
('cat,id2'),
('dog,id3')


SELECT
column1,
SUM(CASE WHEN c2 = 'cat' THEN 1 ELSE 0 END) AS cat,
SUM(CASE WHEN c2 = 'dog' THEN 1 ELSE 0 END) AS dog
FROM
(
SELECT
STUFF(column1,1,CHARINDEX(',',column1),'') column1,
LEFT(column1,CHARINDEX(',',column1)-1) c2
FROM
#data
)s
GROUP BY column1;

DROP TABLE #data
Go to Top of Page

sodeep
Master Smack Fu Yak Hacker

7174 Posts

Posted - 2013-01-17 : 13:37:47
quote:
Originally posted by KidCactus

I'll go straight to my dilemma. I have a table with a column that looks something like this:

column1

dog,id1
cat,id1
cat,id3
dog,id1
dog,id2
cat,id3
cat,id1
dog,id2
cat,id2
dog,id3


I would like to do a query that would give this result in three columns:

column1    cat    dog

id1 2 2
id2 1 2
id3 2 1


I don't even know where to start, but I assume this shouldn't be that hard to obtain?




Why is data stored like this?
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-01-17 : 22:43:11
In the current condition this might be what you're looking at if you've dynamic types of pets

http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx


if its possible try to redesign system to be inline with first normal form.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -