简体   繁体   English

SQL:如何从具有字符串值的列中查找特定类别值的计数

[英]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 我有一个名为“类别”的SQL表看起来像这样

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. “类别”列中有多个类别ID,我需要查找特定类别值的计数。

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. 它提供了所有不同值的计数,因为我需要分别获取所有特定category_id的计数。

if you are trying to get the Category Ids in comma delimited, you can use the string_split function to get distinct category_id 如果您试图以逗号分隔获取Category Ids ,则可以使用string_split函数来获取不同的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: 我以为@ neeraj04可能正在查找类别中所有ID的计数,并以@METAL代码继续:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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