[英]Count distinct records in one column with multiple values in another column
I'm pretty sure this is an easy question, but I'm having trouble wording it. 我很确定这是一个简单的问题,但我在编写问题时遇到了麻烦。
I need to count the total number of values in one column based on distinct criteria in another column. 我需要根据另一列中的不同条件计算一列中的值的总数。
Example: 例:
A CD
B ABC
C AD
D A
Would yield: 会产量:
A 3
B 1
C 2
D 2
First, you shouldn't be storing lists of things in a string. 首先,您不应该在字符串中存储事物列表。
But, sometimes one is stuck with this format. 但是,有时人们会坚持使用这种格式。 In your example, you seem to have a table with all possible values.
在您的示例中,您似乎有一个包含所有可能值的表。 If so you can use a
join
: 如果是这样,您可以使用
join
:
select e.col1, count(e2.col2)
from example e left join
example e2
on charindex(e.col1, e2.col2) > 0
group by e.col1;
Note: this counts rows containing the value rather. 注意:这会计算包含值的行。 If multiple values appear in a single row, the query is a bit more complicated.
如果单个行中出现多个值,则查询会更复杂一些。
Here is how you can do it: 以下是如何做到这一点:
DECLARE @t TABLE ( c1 CHAR(1), c2 VARCHAR(5) )
INSERT INTO @t
VALUES ( 'A', 'CD' ),
( 'B', 'ABC' ),
( 'C', 'AD' ),
( 'D', 'A' )
SELECT t.c1 ,
SUM(count) AS count
FROM @t t
CROSS APPLY ( SELECT LEN(c2) - LEN(REPLACE(c2, t.c1, '')) AS count
FROM @t
WHERE c2 LIKE '%' + t.c1 + '%'
) ca
GROUP BY t.c1
Assuming table is called yourtable and fields are like soo. 假设表被称为yourtable,字段就像soo。
fielda fieldb
A CD
B ABC
C AD
D A
Code 码
SELECT a.fielda, (SELECT COUNT(b.fieldb)
FROM yourtable b
WHERE b.fieldb LIKE '%a.fielda%' AND b.fielda = a.fielda) AS counter
FROM yourtable a
You can use a correlated subquery with LIKE
您可以将相关子查询与
LIKE
Sample Data 样本数据
with cte(a,b) as
(
select 'A','CD'
union all select 'B','ABC'
union all select'C','AD'
union all select'D','A'
)
Query 询问
select a,(select count(*) from cte c2 where b like '%' + c1.a +'%')
from cte c1
group by a
Output 产量
A 3
B 1
C 2
D 2
Use a correlated sub-query when counting. 计数时使用相关的子查询。 Use
LIKE
to find rows to find rows to count. 使用
LIKE
查找行以查找要计数的行。
select t1.col1, (select count(*) from tablename t2
where t2.col2 like '%' || t1.col1 ||'%')
from tablename t1
||
is ANSI SQL concatenation. 是ANSI SQL串联。 Some products use
concat()
, or +
instead. 有些产品使用
concat()
或+
。
Looks like you need a self join there but the trick would be to use a pattern match on the join rather than an equi-join... 看起来你需要一个自我加入,但诀窍是在连接上使用模式匹配而不是equi-join ...
create table x1(c1 char(1) primary key, c2 varchar(5) not null);
select x1.c1, count(*)
from x1 x1
join x1 x2 on x2.c2 like '%' || x1.c1 || '%'
group by x1.c1
order by 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.