0

I have a bad table structure. I try to modify it as little as possible because the real problem is more complicated. I'm working in SQL Server 2005.

Here is my table:

tbl_item

id | item
---+------
1  | car
2  | car
3  | car, => This is what I focus
4  | jet 
5  | jet, car => This is just an example of the comma purpose

Query :

SELECT item, count(*) AS sum 
FROM tbl_item 
GROUP BY item 
ORDER BY sum DESC

Result:

item    | sum
--------+-------
car     | 2
car,    | 1
jet     | 1 
jet,car | 1

What I want is like this:

item     | sum
---------+--------
car      | 3
jet      | 1 
jet, car | 1 => actually I don't care about this, but this just for example

I tried :

SELECT REPLACE(item,',',''), count(*) AS sum 
FROM tbl_item 
GROUP BY item 
ORDER BY sum DESC

But the result is:

item     | sum
---------+------
car      | 2
car      | 1 => still in the different row
jet      | 1 
car, jet | 1

I can manipulate this so easy with PHP, but I wonder how to do this with pure SQL Server.

3
  • @k48 thanks for edit my question Commented Jan 11, 2017 at 2:41
  • 1
    Try to group by replace(item,',','') Commented Jan 11, 2017 at 2:41
  • @detellda work like charm man. can u post your answer. i will sign that for the correct answer Commented Jan 11, 2017 at 2:45

2 Answers 2

3

Try:

GROUP BY REPLACE(item,',','')

This will normalize the items, then group on them.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to add it to the group by clause:

SELECT REPLACE(item,',',''), count(*) AS sum 
FROM tbl_item 
GROUP BY replace(item,',','')
ORDER BY sum DESC

1 Comment

this is the correct answer too, but detellda is the first one who answer. thanks for the help and edit my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.