[英]How to find string count using SQL query of a particular id in a column?
[英]SQL : How to find the count of an particular category values from an column with string values
我有一个名为“类别”的SQL表看起来像这样
id | category
--------------
1 | 3,2
2 | 1
3 | 4,3,2
4 | 2,1
5 | 1,4
6 | 2,3,4
“类别”列中有多个类别ID,我需要查找特定类别值的计数。
我正在使用的当前方法是:
select count(distinct(Category)) AS coldatacount from table_name
它提供了所有不同值的计数,因为我需要分别获取所有特定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, ',');
我以为@ 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;
这是一个可怕的数据模型。 您不应该在字符串中存储多个值。 您不应该将数字存储为字符串。
有时我们会被别人的错误决定所困扰。 一种方法是拆分字符串并计数:
select t.*, cnt
from t cross apply
(select count(*) as cnt
from string_split(t.category) s
) s;
另一种是计算逗号:
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.