简体   繁体   中英

SQL : How to find the count of an particular category values from an column with string values

I have a SQL Table called "category" looks like this

id | category
--------------
1  | 3,2
2  | 1
3  | 4,3,2
4  | 2,1
5  | 1,4
6  | 2,3,4

There are multiple category id's in the column "category", I need to find the count of an particular category values.

Current method I am using is:

select count(distinct(Category)) AS coldatacount from table_name

It gives the count of all the distinct values WHERE as I need to get the count of all the particular category_id's separately.

if you are trying to get the Category Ids in comma delimited, you can use the string_split function to get distinct category_id

with cte as (
    select 1 as id, '3,2' as category union all
    select 2, '1' union all
    select 3, '4,3,2' union all
    select 4, '2,1' union all
    select 5, '1,4' union all
    select 6, '2,3,4' 
)select count(distinct(value)) as category from cte
cross apply string_split(cte.category, ',');

I assumed that @neeraj04 may be looking for count of all Id in the category, continuing with @METAL code:

CREATE TABLE YourTable
 (
 Id INT IDENTITY,
 [Category] VARCHAR(50)
 );

INSERT YourTable VALUES ('3,2'), ('1'), ('4,3,2'), ('2,1'), ('1,4'), ('2,3,4');


SELECT CAST(value AS INT) AS category -- Value is string ouptut
     , COUNT([value]) AS IdCount 
FROM YourTable yt
CROSS APPLY string_split(yt.Category, ',')
GROUP BY [value]
ORDER BY category;

This is a horrible data model. You should not be storing multiple values in a string. You should not be storing numbers as strings.

Sometimes we are stuck with other people's really, really bad decisions. One approach is to split the string and count:

select t.*, cnt
from t cross apply
     (select count(*) as cnt
      from string_split(t.category) s
     )  s;

The other is to count commas:

select t.*,
       (1 + len(t.category) - len(replace(t.category, ',', '')) as num_elements
Select Count(Value) from (Select Value from Table_Name a Cross Apply 
string_split(a.Category, ','))ab Where Value=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM