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.

Neolisk
  • 23,880
  • 16
  • 72
  • 135

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
  • 33,047
  • 7
  • 75
  • 83
0
SELECT COUNT(CarMakes), CarMakes FROM cartable ORDER BY CarMakes ASC
Sablefoste
  • 3,680
  • 3
  • 35
  • 52
  • Your solution assumes `CarMakes` is normalized and it's not. The query would return `(1, "Mercedes, BMW"), (1, "Range Rover"), (1,"Mazda, Toyota, Honda")`. – Neolisk 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
Neolisk
  • 23,880
  • 16
  • 72
  • 135