[英]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.