2

I have a table in SQL. I have a column named CarMakes, it has the following contents:

Mercedes, BMW
Range Rover
Mazda, Toyota, Honda

I want to know how to return a number of CarMakes in each row.

Returned value should be 2, 1 and 3 respectively.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
  • values for `CARMAKES` are separated by a comma? – John Woo Nov 16 '12 at 15:11
  • And what kind of SQL server are you using? – ShyJ Nov 16 '12 at 15:13
  • Yes, the values are separated by comma –  Nov 16 '12 at 15:18
  • 2
    Do ***not*** store multiple values (delimited by something) in a single column. That is a ***very*** bad idea. You should re-design your data model. Then the query will be *very* simple. See here for more information: http://stackoverflow.com/q/3653462/330315 –  Nov 16 '12 at 15:33

3 Answers3

1

This is a MySQL-based answer, so it may be inappropriate for your case if you're using something else. This assumes the values are comma-separated and in the same column (quite an assumption :) ):

SELECT car, (LENGTH(car)-LENGTH(REPLACE(car, ',', ''))+1) AS 'Counts'
FROM CarMakes

I'm sure this will run into issues somewhere, but it may work if your situation doesn't contain random commas. You can see the SQLFiddle here.

RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
0
SELECT COUNT(CarMakes), CarMakes FROM cartable ORDER BY CarMakes ASC
Sablefoste
  • 4,032
  • 3
  • 37
  • 58
  • Your solution assumes `CarMakes` is normalized and it's not. The query would return `(1, "Mercedes, BMW"), (1, "Range Rover"), (1,"Mazda, Toyota, Honda")`. – Victor Zakharov Nov 16 '12 at 15:33
  • @Neolisk, that wasn't defined (or clear) in the original question. Thank goodness for updates and edits. As mentioned by others, the table should be normalized, making this the proper way to query. – Sablefoste Nov 16 '12 at 15:40
0

Assuming T-SQL / MS SQL Server, you have two options:

  1. String.Split - count array elements.
  2. Find occurrence of character in String - count commas.
Community
  • 1
  • 1
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151